FibonacciRetracementHi all!
This library will help you draw Fibonacci retracement levels (zones). The code is from my indicator "Fibonacci retracement" (). You can see that description for more information about the behaviour and example of how to use this library. The code is almost the same with the addition of alerts. If the alert frequency is 'alert.freq_once_per_bar_close' alert messages will be concatenated and have a header saying how many messages it contains (if it's more than 1).
Hope this is of help!
Library "FibonacciRetracement"
ConcateAlerts(context)
Concatenates all alerts from the bar to one string (separated by new lines) and clears alert messages on the current bar.
Parameters:
context (Context)
AddAlert(context, message, unshiftInsteadOfPush)
Parameters:
context (Context)
message (string)
unshiftInsteadOfPush (bool)
Range(context, structure, settings)
Will return values if new levels/zones should be drawn.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement.
structure (Structure type from mickes/PriceAction/1) : The current 'Structure' from the 'MarketStructure' library.
settings (Settings) : The 'Settings' object for the 'Context'.
Returns: A tuple with the start and end pivot if new zones should be drawn, ' ' otherwise.
DrawAll(context, settings, start, end)
Draws lines and labels for the zone. It will also set the 'Price' value that will be used for absolute positions.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement.
settings (Settings) : The 'Settings' object for the 'Context'.
start (Pivot type from mickes/PriceAction/1)
end (Pivot type from mickes/PriceAction/1)
AlertActive(context, settings)
Will alert for all zones that are active. If multiple alert messages are added they will be concatenated (separated by a new line) with a header saying how many messages the alert contains.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement. This contains the zones that will be alerted if price (wick or close according to the settings) enters it.
settings (Settings) : The 'Settings' object for the 'Context'.
TrendlineSettings
Holds all the values for 'TrendlineSettings'.
Fields:
Enabled (series bool) : If the trendline should be visible or not.
Color (series color) : The color of the trendline.
Style (series string) : The style of the trendline (as a string).
GenericZonesSettings
Holds all the values for 'GenericZonesSettings', that will be applicable to all drawn objects.
Fields:
ExtendRight (series bool) : If all lines should extend to the right or not.
Style (series string) : The style of all drawn lines
Reverse (series bool) : If true, all lines will be reversed.
Prices (series bool) : If price levels should be shown or not.
Levels (series bool) : If levels should be shown or not.
LevelsValue (series string) : Either 'Value' or 'Percent'. Defined if value or percentage should be shown.
FontSize (series int) : The for size of the text in labels drawn.
LabelsPosition (series string) : Coul be 'Left', 'Rigth' or 'Adapt'. 'Adapt' will try to adapt the labels position to the prices.
ZoneSettings
Holds all the values for 'ZoneSettings'.
Fields:
Enabled (series bool) : If this zone is enabled or not.
Level (series float) : The level of the zone.
Color (series color) : The color that will be displayed.
Price (series float) : The price of the level. Will be set internally.
Settings
Holds all the values for 'Settings'.
Fields:
PivotLeftLength (series int) : The left length used to find pivots through the 'MarketStructure' library.
PivotRightLength (series int) : The right length used to find pivots through the 'MarketStructure' library.
Trendline (TrendlineSettings) : The settings for the 'Trendline' object.
GenericZonesSettings (GenericZonesSettings) : The setting applicable to all zones.
AlertFrequency (series string) : The frequency for the alerts. If 'alert.freq_once_per_bar_close', alert messages will be concatenated and have a header saying how many messages it contains (if it's more than 1).
AlertPrice (series string) : The price that has to enter a zone. Can be 'Close' (the closing price) or 'Wick' (the whole candle needs to be in the zone).
Zone1 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone2 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone3 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone4 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone5 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone6 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone7 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone8 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone9 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone10 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone11 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone12 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone13 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone14 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone15 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone16 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone17 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone18 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone19 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone20 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone21 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone22 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone23 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone24 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Context
Holds all the values for 'Context'.
Fields:
Lines (array) : All the drawn lines for the current 'Context'.
Labels (array) : All the drawn labels for the current 'Context'.
Boxes (array) : All the drawn boxes for the current 'Context'.
Alerts (array) : All the alert messages on the current tick.
Start (series int) : The start bar index of the current 'Context'.
Display
PriceActionLibrary "PriceAction"
Hi all!
This library will help you to plot the market structure and liquidity. By now, the only part in the price action section is liquidity, but I plan to add more later on. The market structure will be split into two parts, 'Internal' and 'Swing' with separate pivot lengths. For these two trends it will show you:
• Break of structure (BOS)
• Change of character (CHoCH/CHoCH+) (mandatory)
• Equal high/low (EQH/EQL)
It's inspired by "Smart Money Concepts (SMC) " by LuxAlgo.
This library is now the same code as the code in my library 'MarketStructure', but it has evolved into a more price action oriented library than just a market structure library. This is more accurate and I will continue working on this library to keep it growing.
This code does not provide any examples, but you can look at my indicators 'Market structure' () and 'Order blocks' (), where I use the 'MarketStructure' library (which is the same code).
Market structure
Both of these market structures can be enabled/disabled by setting them to 'na'. The pivots lengths can be configured separately. The pivots found will be the 'base' of and will show you when price breaks it. When that happens a break of structure or a change of character will be created. The latest 5 pivots found within the current trends will be kept to take action on. They are cleared on a change of character, so nothing (break of structures or change of characters) can happen on pivots before a trend change. The internal market structure is shown with dashed lines and swing market structure is shown with solid lines.
Labels for a change of character can have either the text 'CHoCH' or 'CHoCH+'. A Change of Character plus is formed when price fails to form a higher high or a lower low before reversing. Note that a pivot that is created after the change of character might have a higher high or a lower low, thus not making the break a 'CHoCH+'. This is not changed after the pivot is found but is kept as is.
A break of structure is removed if an earlier pivot within the same trend is broken, i.e. another break of structure (with a longer distance) is created. Like in the images below, the first pivot (in the first image) is removed when an earlier pivot's higher price within the same trend is broken (the second image):
[image [https://www.tradingview.com/x/PRP6YtPA/
Equal high/lows have a configurable color setting and can be configured to be extended to the right. Equal high/lows are only possible if it's not been broken by price. A factor (percentage of width) of the Average True Length (of length 14) that the pivot must be within to to be considered an Equal high/low. Equal highs/lows can be of 2 pivots or more.
You are able to show the pivots that are used. "HH" (higher high), "HL" (higher low), "LH" (lower high), "LL" (lower low) and "H"/"L" (for pivots (high/low) when the trend has changed) are the labels used. There are also labels for break of structures ('BOS') and change of characters ('CHoCH' or 'CHoCH+'). The size of these texts is set in the 'FontSize' setting.
When programming I focused on simplicity and ease of read. I did not focus on performance, I will do so if it's a problem (haven't noticed it is one yet).
You can set alerts for when a change of character, break of structure or an equal high/low (new or an addition to a previously found) happens. The alerts that are fired are on 'once_per_bar_close' to avoid repainting. This has the drawback to alert you when the bar closes.
Price action
The indicator will create lines and zones for spotted liquidity. It will draw a line (with dotted style) at the price level that was liquidated, but it will also draw a zone from that level to the bar that broke the pivot high or low price. If that zone is large the liquidation is big and might be significant. This can be disabled in the settings. You can also change the confirmation candles (that does not close above or below the pivot level) needed after a liquidation and how many pivots back to look at.
The lines and boxes drawn will look like this if the color is orange:
Hope this is of help!
Will draw out the market structure for the disired pivot length.
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: A boolean that represents if a break of structure was found or not.
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: A boolean that represents if a change of character was found or not.
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.
ZV-Resources by ZuperView.comLibrary "zuperview"
ComputeMAValue(maType, series, period)
ComputeMAValue
@description Computes the moving average (MA) value based on the specified MA type.
Parameters:
maType (string) : (string) The type of moving average: "EMA", "SMA", "RMA", "WMA", "HMA", "VWMA", "LinReg".
series (float) : (float) The input price series (typically close).
period (simple int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed MA value or `na` if maType is invalid.
ComputeATRValue(period)
ComputeATRValue
@description Computes the moving average (ATR) value based on the specified ATR type.
Parameters:
period (int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed ATR value or `na` if maType is invalid.
Max(src, period)
Parameters:
src (float)
period (int)
Min(src, period)
Parameters:
src (float)
period (int)
ComputeRSIValue(src, period, smooth)
ComputeRSIValue
@description Computes the moving average (RSI) value based on the specified RSI type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
period (int) : (int) The number of periods used for MA calculation.
smooth (int)
Returns: (float) The computed RSI value or `na` if maType is invalid.
ComputeSMMAValue(src, period)
ComputeSMMAValue
@description Computes the moving average (SMMA) value based on the specified SMMA type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
period (int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed SMMA value or `na` if maType is invalid.
ComputeStochasticValue(src, periodD, periodK, smoothingMethod, smoothingPeriod)
ComputeStochasticValue
@description Computes the moving average (SMMA) value based on the specified SMMA type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
periodD (simple int) : (int) The number of periods used for MA calculation.
periodK (int) : (int) The number of periods used for MA calculation.
smoothingMethod (string) : (string) The type of moving average: "EMA", "SMA", "RMA", "WMA", "HMA", "VWMA", "LinReg".
smoothingPeriod (simple int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed Stochastic(K, D) value or `na` if maType is invalid.
BarLibrary "Bar"
A comprehensive library for creating and managing custom multi-timeframe (MTF) candlestick bars without using request.security calls, providing enhanced visualization and analytical capabilities with improved performance
Candle()
Creates a new candle object initialized with current bar's OHLC data
Returns: A new _Candle instance with current market data
method body(this)
Calculates the absolute size of the candle body (distance between open and close)
Namespace types: _Candle
Parameters:
this (_Candle)
Returns: The absolute difference between closing and opening prices
method topWick(this)
Calculates the length of the upper wick (shadow above the candle body)
Namespace types: _Candle
Parameters:
this (_Candle)
Returns: The distance from the higher of open/close to the high price
method bottomWick(this)
Calculates the length of the lower wick (shadow below the candle body)
Namespace types: _Candle
Parameters:
this (_Candle)
Returns: The distance from the low price to the lower of open/close
method display(this, bullishColor, bearishColor, transp, borderWidth, lineWidth)
Renders the candle visually on the chart with customizable colors and styling options
Namespace types: _Candle
Parameters:
this (_Candle)
bullishColor (color)
bearishColor (color)
transp (int)
borderWidth (int)
lineWidth (int)
candles(tf, autoDisplay)
Creates and manages an array of custom timeframe candles with optional automatic display
Parameters:
tf (string) : Target timeframe string (e.g., "60", "240", "D") for candle aggregation
autoDisplay (bool)
Returns: Array containing all completed candles for the specified timeframe
_Candle
Custom candlestick data structure that stores OHLCV data with visual rendering components
Fields:
start (series int) : Opening timestamp of the candle period
end (series int) : Closing timestamp of the candle period
o (series float) : Opening price of the candle
h (series float) : Highest price reached during the candle period
l (series float) : Lowest price reached during the candle period
c (series float) : Closing price of the candle
v (series float) : Volume traded during the candle period
bodyBox (series box)
wickLine (series line)
Example Usage
// Change version with latest version
import EmreKb/Bar/1 as bar
// "240" for 4h timeframe
// true for auto display candles on chart (default: false)
candlesArr = bar.candles("240", true)
zuperviewResourcesLibrary "zuperview"
ComputeMAValue(maType, series, period)
ComputeMAValue
@description Computes the moving average (MA) value based on the specified MA type.
Parameters:
maType (string) : (string) The type of moving average: "EMA", "SMA", "RMA", "WMA", "HMA", "VWMA", "LinReg".
series (float) : (float) The input price series (typically close).
period (simple int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed MA value or `na` if maType is invalid.
ComputeATRValue(period)
ComputeATRValue
@description Computes the moving average (ATR) value based on the specified ATR type.
Parameters:
period (int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed ATR value or `na` if maType is invalid.
Max(src, period)
Parameters:
src (float)
period (int)
Min(src, period)
Parameters:
src (float)
period (int)
ComputeRSIValue(src, period, smooth)
ComputeRSIValue
@description Computes the moving average (RSI) value based on the specified RSI type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
period (int) : (int) The number of periods used for MA calculation.
smooth (int)
Returns: (float) The computed RSI value or `na` if maType is invalid.
ComputeSMMAValue(src, period)
ComputeSMMAValue
@description Computes the moving average (SMMA) value based on the specified SMMA type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
period (int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed SMMA value or `na` if maType is invalid.
ComputeStochasticValue(src, periodD, periodK, smoothingMethod, smoothingPeriod)
ComputeStochasticValue
@description Computes the moving average (SMMA) value based on the specified SMMA type.
Parameters:
src (float) : (series) Input series (series float), which can be close (`close`), open (`open`), high (`high`), low (`low`), or any other price-based series.
periodD (simple int) : (int) The number of periods used for MA calculation.
periodK (int) : (int) The number of periods used for MA calculation.
smoothingMethod (string) : (string) The type of moving average: "EMA", "SMA", "RMA", "WMA", "HMA", "VWMA", "LinReg".
smoothingPeriod (simple int) : (int) The number of periods used for MA calculation.
Returns: (float) The computed Stochastic(K, D) value or `na` if maType is invalid.
FindSwingsByNeighborhood(arraySwingTop, arraySwingBottom, neighborhood)
Find Swings By Neighborhood
@description Computes the moving average (SMMA) value based on the specified SMMA type.
Parameters:
arraySwingTop (array) : (array): An array to store detected swing highs.
arraySwingBottom (array) : (array): An array to store detected swing lows.
neighborhood (int) : (int): The number of bars to consider when identifying a swing point.
Returns: none
FindSwingsByOffset(arraySwingTop, arraySwingBottom, minSwingLength)
Find Swings By Offset
@description Identifies swing points based on a minimum swing length criteria.
Parameters:
arraySwingTop (array) : (array): An array to store detected swing highs.
arraySwingBottom (array) : (array): An array to store detected swing lows.
minSwingLength (float) : (float): The minimum price movement required to qualify as a swing point.
Returns: none
SwingPoint
Fields:
Key (series int)
IsTop (series bool)
Price (series float)
BarStart (series int)
BarEnd (series int)
TimeStart (series int)
TimeEnd (series int)
Sign (series int)
Label (series label)
BecakFloatingPanelsLibrary "BecakFloatingPanels"
Library for creating floating indicator panels with MACD, RSI, and Stochastic indicators
calculateMacd(source, fastLength, slowLength, signalLength)
Calculate MACD components
Parameters:
source (float) : Price source for calculation
fastLength (simple int) : Fast EMA period
slowLength (simple int) : Slow EMA period
signalLength (simple int) : Signal line period
Returns: MacdData MACD calculation results
calculateRsi(source, length)
Calculate RSI
Parameters:
source (float) : Price source for calculation
length (simple int) : RSI period
Returns: float RSI value
calculateStochastic(source, high, low, kLength, kSmoothing, dSmoothing)
Calculate Stochastic components
Parameters:
source (float) : Price source for calculation
high (float) : High prices
low (float) : Low prices
kLength (int) : %K period
kSmoothing (int) : %K smoothing period
dSmoothing (int) : %D smoothing period
Returns: StochData Stochastic calculation results
calculateStochSignals(stochK, stochD, overboughtLevel, oversoldLevel)
Calculate Stochastic signals
Parameters:
stochK (float) : Stochastic %K series
stochD (float) : Stochastic %D series
overboughtLevel (float) : Overbought threshold
oversoldLevel (float) : Oversold threshold
Returns: StochSignals Signal flags
calculateChartMetrics(high, low, lookbackLength)
Calculate chart range and positioning metrics
Parameters:
high (float) : High prices
low (float) : Low prices
lookbackLength (int) : Lookback period
Returns: ChartMetrics Chart positioning data
calculateMacdRange(macdLine, signalLine, histogram, safeLookback)
Calculate MACD range for normalization
Parameters:
macdLine (float) : MACD line series
signalLine (float) : Signal line series
histogram (float) : Histogram series
safeLookback (int) : Lookback period
Returns: MacdRange MACD range metrics
initVisualArrays()
Initialize visual arrays
Returns: VisualArrays Container with initialized arrays
clearVisuals(visuals)
Clear all visual elements
Parameters:
visuals (VisualArrays) : VisualArrays container
Returns: void
calculatePanelPositions(chartMetrics, oscPlacement, panelHeight, panelSpacing, centerOffset)
Calculate panel positions based on placement option
Parameters:
chartMetrics (ChartMetrics) : Chart metrics object
oscPlacement (string) : Panel placement option
panelHeight (float) : Panel height percentage
panelSpacing (float) : Panel spacing percentage
centerOffset (float) : Center offset percentage
Returns: PanelPositions Panel boundary coordinates
createPanelBackgrounds(visuals, positions, panelLeft, panelRight, showBackground, transparency)
Create panel backgrounds
Parameters:
visuals (VisualArrays) : VisualArrays container
positions (PanelPositions) : PanelPositions object
panelLeft (int) : Left boundary
panelRight (int) : Right boundary
showBackground (bool) : Show background flag
transparency (int) : Background transparency
Returns: void
drawReferenceLines(visuals, positions, chartMetrics, macdRange, dataLeft, dataRight, panelHeight, rsiOverbought, rsiOversold, stochOverbought, stochOversold)
Draw reference lines for all panels
Parameters:
visuals (VisualArrays) : VisualArrays container
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
macdRange (MacdRange) : MacdRange object
dataLeft (int) : Left data boundary
dataRight (int) : Right data boundary
panelHeight (float) : Panel height percentage
rsiOverbought (int) : RSI overbought level
rsiOversold (int) : RSI oversold level
stochOverbought (int) : Stochastic overbought level
stochOversold (int) : Stochastic oversold level
Returns: void
drawMacdIndicator(visuals, macdLine, signalLine, histogram, macdRange, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight)
Draw MACD indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
macdLine (float) : MACD line series
signalLine (float) : Signal line series
histogram (float) : Histogram series
macdRange (MacdRange) : MacdRange object
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
Returns: void
drawRsiIndicator(visuals, rsiValue, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight)
Draw RSI indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
rsiValue (float) : RSI value
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
Returns: void
drawStochasticIndicator(visuals, stochK, stochD, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight, stochOverbought, stochOversold)
Draw Stochastic indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
stochK (float) : Stochastic %K series
stochD (float) : Stochastic %D series
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
stochOverbought (int) : Overbought level
stochOversold (int) : Oversold level
Returns: void
addStochasticSignals(visuals, buySignal, sellSignal, positions, chartMetrics, currentBarIndex, barIndexOffset, panelHeight, signalIndex)
Add Stochastic buy/sell signals
Parameters:
visuals (VisualArrays) : VisualArrays container
buySignal (bool) : Buy signal series
sellSignal (bool) : Sell signal series
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
currentBarIndex (int) : Current bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
signalIndex (int) : Signal index for lookback
Returns: void
setPanelLabels(macdLabel, rsiLabel, stochLabel, positions, chartMetrics, labelOffset, panelHeight, barIndexOffset)
Set panel title labels
Parameters:
macdLabel (label) : MACD label reference
rsiLabel (label) : RSI label reference
stochLabel (label) : Stochastic label reference
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
labelOffset (int) : Label horizontal offset
panelHeight (float) : Panel height percentage
barIndexOffset (int) : Horizontal offset
Returns: void
showDebugInfo(chartMetrics, debugMode)
Display debug information
Parameters:
chartMetrics (ChartMetrics) : ChartMetrics object
debugMode (bool) : Debug mode flag
Returns: void
ChartMetrics
Chart metrics container
Fields:
visibleHigh (series float) : Highest visible price
visibleLow (series float) : Lowest visible price
chartRange (series float) : Price range of chart
chartCenter (series float) : Center point of chart
MacdData
MACD calculation results
Fields:
macdLine (series float) : Main MACD line
signalLine (series float) : Signal line
histogram (series float) : MACD histogram
MacdRange
MACD range metrics for normalization
Fields:
highest (series float) : Highest MACD value
lowest (series float) : Lowest MACD value
BRange (series float) : Total range
StochData
Stochastic calculation results
Fields:
k_smooth (series float) : Smoothed %K line
d (series float) : %D line
StochSignals
Stochastic signals
Fields:
buySignal (series bool) : Buy signal flag
sellSignal (series bool) : Sell signal flag
PanelPositions
Panel positioning data
Fields:
macdTop (series float) : MACD panel top
macdBottom (series float) : MACD panel bottom
rsiTop (series float) : RSI panel top
rsiBottom (series float) : RSI panel bottom
stochTop (series float) : Stochastic panel top
stochBottom (series float) : Stochastic panel bottom
VisualArrays
Visual elements arrays container
Fields:
macdLines (array) : Array of MACD lines
macdHist (array) : Array of MACD histogram boxes
rsiLines (array) : Array of RSI lines
stochLines (array) : Array of Stochastic lines
stochAreas (array) : Array of Stochastic areas
stochSignals (array) : Array of Stochastic signals
panelBackgrounds (array) : Array of panel backgrounds
MarketStructureLibMarketStructure Library
This library extends the "MarketStructure" library by mickes () under the Mozilla Public License 2.0, credited to mickes. It provides functions for detecting and visualizing market structure, including Break of Structure (BOS), Change of Character (CHoCH), Equal High/Low (EQH/EQL), and liquidity zones, with enhancements for improved accuracy and customization.
Functionality
Market Structure Detection: Identifies internal (orderflow) and swing market structures using pivot points, with support for BOS, CHoCH, and EQH/EQL.
Volatility Filter: Only confirms pivots when the ATR exceeds a user-defined threshold, reducing false signals in low-volatility markets.
Trend Strength Metric: Calculates a trend strength score based on pivot frequency and volatility, stored in the Structure type for use in scripts.
Customizable Visualizations: Allows users to configure line styles and colors for BOS and CHoCH, and label sizes for pivots, BOS, CHoCH, and liquidity.
Liquidity Zones: Visualizes liquidity levels with confirmation bars and lookback periods.
Methodology
Pivot Detection: Uses ta.pivothigh and ta.pivotlow with a volatility filter (ATR multiplier) to confirm significant pivots.
Trend Strength: Computes a score as pivotCount / LeftLength * (currentATR / ATR), reflecting trend reliability based on pivot frequency and market volatility.
BOS/CHoCH Logic: Detects BOS when price breaks a pivot in the trend direction, and CHoCH when price reverses against the trend, with labels for "MSF" or "MSF+" based on pivot patterns.
EQH/EQL Zones: Creates boxes around equal highs/lows within an ATR-based threshold, with optional extension.
Visualization: Draws lines and labels for BOS, CHoCH, and liquidity, with user-defined styles, colors, and sizes.
Usage
Integration: Import into Pine Script indicators (e.g., import Fenomentn/MarketStructure/1) to analyze market structure.
Configuration: Set pivot lengths, volatility threshold, label sizes, and visualization styles via script inputs.
Alerts: Enable alerts for BOS, CHoCH, and EQH/EQL events, triggered on bar close to avoid repainting.
Best Practices: Use on forex or crypto charts (1m to 12h timeframes) for optimal results. Adjust the volatility threshold for different market conditions.
Originality
This library builds on mickes’ framework by adding:
A volatility-based pivot filter to enhance signal accuracy.
A trend strength metric for assessing trend reliability.
Dynamic label sizing and customizable visualization styles for better usability. No additional open-source code was reused beyond mickes’ library, credited under MPL 2.0.
Developed by Fenomentn. Published under Mozilla Public License 2.0.
Correlation HeatMap Matrix Data [TradingFinder]🔵 Introduction
Correlation is a statistical measure that shows the degree and direction of a linear relationship between two assets.
Its value ranges from -1 to +1 : +1 means perfect positive correlation, 0 means no linear relationship, and -1 means perfect negative correlation.
In financial markets, correlation is used for portfolio diversification, risk management, pairs trading, intermarket analysis, and identifying divergences.
Correlation HeatMap Matrix Data TradingFinder is a Pine Script v6 library that calculates and returns raw correlation matrix data between up to 20 symbols. It only provides the data – it does not draw or render the heatmap – making it ideal for use in other scripts that handle visualization or further analysis. The library uses ta.correlation for fast and accurate calculations.
It also includes two helper functions for visual styling :
CorrelationColor(corr) : takes the correlation value as input and generates a smooth gradient color, ranging from strong negative to strong positive correlation.
CorrelationTextColor(corr) : takes the correlation value as input and returns a text color that ensures optimal contrast over the background color.
Library
"Correlation_HeatMap_Matrix_Data_TradingFinder"
CorrelationColor(corr)
Parameters:
corr (float)
CorrelationTextColor(corr)
Parameters:
corr (float)
Data_Matrix(Corr_Period, Sym_1, Sym_2, Sym_3, Sym_4, Sym_5, Sym_6, Sym_7, Sym_8, Sym_9, Sym_10, Sym_11, Sym_12, Sym_13, Sym_14, Sym_15, Sym_16, Sym_17, Sym_18, Sym_19, Sym_20)
Parameters:
Corr_Period (int)
Sym_1 (string)
Sym_2 (string)
Sym_3 (string)
Sym_4 (string)
Sym_5 (string)
Sym_6 (string)
Sym_7 (string)
Sym_8 (string)
Sym_9 (string)
Sym_10 (string)
Sym_11 (string)
Sym_12 (string)
Sym_13 (string)
Sym_14 (string)
Sym_15 (string)
Sym_16 (string)
Sym_17 (string)
Sym_18 (string)
Sym_19 (string)
Sym_20 (string)
🔵 How to use
Import the library into your Pine Script using the import keyword and its full namespace.
Decide how many symbols you want to include in your correlation matrix (up to 20). Each symbol must be provided as a string, for example FX:EURUSD .
Choose the correlation period (Corr\_Period) in bars. This is the lookback window used for the calculation, such as 20, 50, or 100 bars.
Call Data_Matrix(Corr_Period, Sym_1, ..., Sym_20) with your selected parameters. The function will return an array containing the correlation values for every symbol pair (upper triangle of the matrix plus diagonal).
For example :
var string Sym_1 = '' , var string Sym_2 = '' , var string Sym_3 = '' , var string Sym_4 = '' , var string Sym_5 = '' , var string Sym_6 = '' , var string Sym_7 = '' , var string Sym_8 = '' , var string Sym_9 = '' , var string Sym_10 = ''
var string Sym_11 = '', var string Sym_12 = '', var string Sym_13 = '', var string Sym_14 = '', var string Sym_15 = '', var string Sym_16 = '', var string Sym_17 = '', var string Sym_18 = '', var string Sym_19 = '', var string Sym_20 = ''
switch Market
'Forex' => Sym_1 := 'EURUSD' , Sym_2 := 'GBPUSD' , Sym_3 := 'USDJPY' , Sym_4 := 'USDCHF' , Sym_5 := 'USDCAD' , Sym_6 := 'AUDUSD' , Sym_7 := 'NZDUSD' , Sym_8 := 'EURJPY' , Sym_9 := 'EURGBP' , Sym_10 := 'GBPJPY'
,Sym_11 := 'AUDJPY', Sym_12 := 'EURCHF', Sym_13 := 'EURCAD', Sym_14 := 'GBPCAD', Sym_15 := 'CADJPY', Sym_16 := 'CHFJPY', Sym_17 := 'NZDJPY', Sym_18 := 'AUDNZD', Sym_19 := 'USDSEK' , Sym_20 := 'USDNOK'
'Stock' => Sym_1 := 'NVDA' , Sym_2 := 'AAPL' , Sym_3 := 'GOOGL' , Sym_4 := 'GOOG' , Sym_5 := 'META' , Sym_6 := 'MSFT' , Sym_7 := 'AMZN' , Sym_8 := 'AVGO' , Sym_9 := 'TSLA' , Sym_10 := 'BRK.B'
,Sym_11 := 'UNH' , Sym_12 := 'V' , Sym_13 := 'JPM' , Sym_14 := 'WMT' , Sym_15 := 'LLY' , Sym_16 := 'ORCL', Sym_17 := 'HD' , Sym_18 := 'JNJ' , Sym_19 := 'MA' , Sym_20 := 'COST'
'Crypto' => Sym_1 := 'BTCUSD' , Sym_2 := 'ETHUSD' , Sym_3 := 'BNBUSD' , Sym_4 := 'XRPUSD' , Sym_5 := 'SOLUSD' , Sym_6 := 'ADAUSD' , Sym_7 := 'DOGEUSD' , Sym_8 := 'AVAXUSD' , Sym_9 := 'DOTUSD' , Sym_10 := 'TRXUSD'
,Sym_11 := 'LTCUSD' , Sym_12 := 'LINKUSD', Sym_13 := 'UNIUSD', Sym_14 := 'ATOMUSD', Sym_15 := 'ICPUSD', Sym_16 := 'ARBUSD', Sym_17 := 'APTUSD', Sym_18 := 'FILUSD', Sym_19 := 'OPUSD' , Sym_20 := 'USDT.D'
'Custom' => Sym_1 := Sym_1_C , Sym_2 := Sym_2_C , Sym_3 := Sym_3_C , Sym_4 := Sym_4_C , Sym_5 := Sym_5_C , Sym_6 := Sym_6_C , Sym_7 := Sym_7_C , Sym_8 := Sym_8_C , Sym_9 := Sym_9_C , Sym_10 := Sym_10_C
,Sym_11 := Sym_11_C, Sym_12 := Sym_12_C, Sym_13 := Sym_13_C, Sym_14 := Sym_14_C, Sym_15 := Sym_15_C, Sym_16 := Sym_16_C, Sym_17 := Sym_17_C, Sym_18 := Sym_18_C, Sym_19 := Sym_19_C , Sym_20 := Sym_20_C
= Corr.Data_Matrix(Corr_period, Sym_1 ,Sym_2 ,Sym_3 ,Sym_4 ,Sym_5 ,Sym_6 ,Sym_7 ,Sym_8 ,Sym_9 ,Sym_10,Sym_11,Sym_12,Sym_13,Sym_14,Sym_15,Sym_16,Sym_17,Sym_18,Sym_19,Sym_20)
Loop through or index into this array to retrieve each correlation value for your custom layout or logic.
Pass each correlation value to CorrelationColor() to get the corresponding gradient background color, which reflects the correlation’s strength and direction (negative to positive).
For example :
Corr.CorrelationColor(SYM_3_10)
Pass the same correlation value to CorrelationTextColor() to get the correct text color for readability against that background.
For example :
Corr.CorrelationTextColor(SYM_1_1)
Use these colors in a table or label to render your own heatmap or any other visualization you need.
thors_forex_factory_decodingLibrary "forex_factory_decoding"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for formatting and saving Forex Factory News events.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
MMM(M)
Converts a month from a numerical integer format to a MMM format (i.e. 'Jan').
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Month in MMM format (i.e. 'Jan').
array2string(S, FWD)
Converts a string array to a simple string, concatenating its elements.
Parameters:
S (array) : String array, or string array slice, to turn into a simple string.
FWD (bool) : Boolean defaulted to True. If True the array will be concatenated from head to tail, reversed order if False.
Returns: Returns the simple string equivalent of the provided string array.
month2number(M)
Converts a month string in 'MMM' format to its integer equivalent.
Parameters:
M (string) : Month string, in 'MMM' format.
Returns: Returns the integer equivalent of the provided Month string in 'MMM' format.
shiftFWD_Days(D)
Shifts forward the current Date by N days.
Parameters:
D (int) : Number of days to forward-shift, default is 7.
Returns: Returns the forward-shifted date in 'MMM %D' format (i.e. Jan 8, Sep 12).
ff_dow(D)
Converts a numbered day of the week string in format to 'DDD' format (i.e. "1" = Sun).
Parameters:
D (string) : Numbered day of the week from 1 to 7, starting on Sunday.
Returns: Returns the day of the week in 'DDD' format (i.e. "Fri").
ff_currency(C)
Converts a numbered currency string in format to 'CCC' format (i.e. "1" = AUD).
Parameters:
C (string) : Numbered currency, where "1" = "AUD", "2" = "CAD", "3" = "CHF", "4" = "CNY", "5" = "EUR", "6" = "GBP", "7" = "JPY", "8" = "NZD", "9" = "USD".
Returns: Returns the currency in 'CCC' format (i.e. "USD").
ff_t(T)
Converts a time of the day in 'hhmm' format into an intger.
Parameters:
T (string) : Time of the day string in 'hhmm' format.
Returns: Returns the time of the day integer in 'hhmm' format, or -1 if all day.
ff_tod(T)
Converts a time of the day from an integer 'hhmm' format into 'hh:mm' format.
Parameters:
T (int)
Returns: Returns the N Forex Factory News array with time of the day string in 'hh:mm' format, or 'All Day'.
ff_impact(I)
Converts a number from 1 to 4 to a relative color based on Forex Factory Impact types.
Parameters:
I (string) : Impact number string from 1 to 4, where "1" = Holiday, "2" = Low Impact, "3" = Medium Impact, "4" = High Impact.
Returns: Returns the color associated to the impact number based on Forex Factory Impact types.
ff_tmst(D, T)
Parameters:
D (string)
T (string)
decode(ID)
Decodes TOODEGREES_FOREX_FACTORY_SLOT_n Symbols' Pine Seeds data into Forex Factory News Events.
Parameters:
ID (int) : Identifier of the Forex Factory News Event, in "DCHHMMI%T" format (D = day of the week from 1 to 7, C = currency from 1 to 9, HHMM = hour:minute in 24h, I = impact from 1 to 4, %T = event title ID) .
Returns: Returns the Forex Factory News Event.
method pullNews(N, n)
Decodes the Forex Factory News Event and adds it to the Forex Factory News array.
Namespace types: array
Parameters:
N (array type from cegb001/forex_factory_utility/1) : Forex Factory News array.
n (float) : imported data from custom feed.
Returns: void
method readNews(N, S)
Pulls the individual Forex Factory News Event from the custom data feed format (joint News string), decodes them and adds them to the Forex Factory News array.
Namespace types: array
Parameters:
N (array type from cegb001/forex_factory_utility/1) : Forex Factory News array.
S (string) : joint string of the imported data from custom feed.
Returns: void
thors_forex_factory_utilityLibrary "forex_factory_utility"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for data handling, and plotting news event data.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
MMM(M)
Converts a month from a numerical integer format to a MMM format (i.e. 'Jan').
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Month in MMM format (i.e. 'Jan').
dow(D)
Converts a numbered day of the week string in format to 'DDD' format (i.e. "1" = Sun).
Parameters:
D (string) : Numbered day of the week from 1 to 7, starting on Sunday.
Returns: Returns the day of the week in 'DDD' format (i.e. "Fri").
size(S, N)
Converts a size string into the corresponding Pine Script v5 format, or N times smaller/bigger.
Parameters:
S (string) : Size string: "Tiny", "Small", "Normal", "Large", or "Huge".
N (int) : Size variation, can be positive (larger than S), or negative (smaller than S).
Returns: Size string in Pine Script v5 format.
lineStyle(S)
Converts a line style string into the corresponding Pine Script v5 format.
Parameters:
S (string) : Line style string: "Dashed", "Dotted" or "Solid".
Returns: Line style string in Pine Script v5 format.
lineTrnsp(S)
Converts a transparency style string into the corresponding integer value.
Parameters:
S (string) : Line style string: "Light", "Medium" or "Heavy".
Returns: Transparency integer.
boxLoc(X, Y)
Converts position strings of X and Y into a table position in Pine Script v5 format.
Parameters:
X (string) : X-axis string: "Left", "Center", or "Right".
Y (string) : Y-axis string: "Top", "Middle", or "Bottom".
Returns: Table location string in Pine Script v5 format.
method bubbleSort_NewsTOD(N)
Performs bubble sort on a Forex Factory News array of all news from the same date, ordering them in ascending order based on the time of the day.
Namespace types: array
Parameters:
N (array) : Forex Factory News array.
Returns: void
bubbleSort_News(N)
Performs bubble sort on a Forex Factory News array, ordering them in ascending order based on the time of the day, and date.
Parameters:
N (array) : Forex Factory News array.
Returns: Sorted Forex Factory News array.
weekNews(N, C, I)
Creates a Forex Factory News array containing the current week's Forex Factory News.
Parameters:
N (array) : Forex Factory News array containing this week's unfiltered Forex Factory News.
C (array) : Currency filter array (string array).
I (array) : Impact filter array (color array).
Returns: Forex Factory News array containing the current week's Forex Factory News.
todayNews(W, D, M)
Creates a Forex Factory News array containing the current day's Forex Factory News.
Parameters:
W (array) : Forex Factory News array containing this week's Forex Factory News.
D (array) : Forex Factory News array for the current day's Forex Factory News.
M (bool) : Boolean that marks whether the current chart has a Day candle-switch at Midnight New York Time.
Returns: Forex Factory News array containing the current day's Forex Factory News.
adjustTimezone(N, TZH, TZM)
Transposes the Time of the Day, and Date, in the Forex Factory News Table to a custom Timezone.
Parameters:
N (array) : Forex Factory News array.
TZH (int) : Custom Timezone hour.
TZM (int) : Custom Timezone minute.
Returns: Reformatted Forex Factory News array.
NewsAMPM_TOD(N)
Reformats the Time of the Day in the Forex Factory News Table to AM/PM format.
Parameters:
N (array) : Forex Factory News array.
Returns: Reformatted Forex Factory News array.
impFilter(X, L, M, H)
Creates a filter array from the User's desired Forex Facory News to be shown based on Impact.
Parameters:
X (bool) : Boolean - if True Holidays listed on Forex Factory will be shown.
L (bool) : Boolean - if True Low Impact listed on Forex Factory News will be shown.
M (bool) : Boolean - if True Medium Impact listed on Forex Factory News will be shown.
H (bool) : Boolean - if True High Impact listed on Forex Factory News will be shown.
Returns: Color array with the colors corresponding to the Forex Factory News to be shown.
curFilter(A, C1, C2, C3, C4, C5, C6, C7, C8, C9)
Creates a filter array from the User's desired Forex Facory News to be shown based on Currency.
Parameters:
A (bool) : Boolean - if True News related to the current Chart's symbol listed on Forex Factory will be shown.
C1 (bool) : Boolean - if True News related to the Australian Dollar listed on Forex Factory will be shown.
C2 (bool) : Boolean - if True News related to the Canadian Dollar listed on Forex Factory will be shown.
C3 (bool) : Boolean - if True News related to the Swiss Franc listed on Forex Factory will be shown.
C4 (bool) : Boolean - if True News related to the Chinese Yuan listed on Forex Factory will be shown.
C5 (bool) : Boolean - if True News related to the Euro listed on Forex Factory will be shown.
C6 (bool) : Boolean - if True News related to the British Pound listed on Forex Factory will be shown.
C7 (bool) : Boolean - if True News related to the Japanese Yen listed on Forex Factory will be shown.
C8 (bool) : Boolean - if True News related to the New Zealand Dollar listed on Forex Factory will be shown.
C9 (bool) : Boolean - if True News related to the US Dollar listed on Forex Factory will be shown.
Returns: String array with the currencies corresponding to the Forex Factory News to be shown.
FF_OnChartLine(N, T, S)
Plots vertical lines where a Forex Factory News event will occur, or has already occurred.
Parameters:
N (array) : News-type array containing all the Forex Factory News.
T (int) : Transparency integer value (0-100) for the lines.
S (string) : Line style in Pine Script v5 format.
Returns: void
method updateStringMatrix(M, P, V)
Updates a string Matrix containing the tooltips for Forex Factory News Event information for a given candle.
Namespace types: matrix
Parameters:
M (matrix) : String matrix.
P (int) : Position (row) of the Matrix to update based on the impact.
V (string) : information to push to the Matrix.
Returns: void
FF_OnChartLabel(N, Y, S, O)
Plots labels where a Forex Factory News has already occurred based on its/their impact.
Parameters:
N (array) : News-type array containing all the Forex Factory News.
Y (string) : String that gives direction on where to plot the label (options= "Above", "Below", "Auto").
S (string) : Label size in Pine Script v5 format.
O (bool) : Show outline of labels?
Returns: void
historical(T, D, W, X)
Deletes Forex Factory News drawings which are ourside a specific Time window.
Parameters:
T (int) : Number of days input used for Forex Factory News drawings' history.
D (bool) : Boolean that when true will only display Forex Factory News drawings of the current day.
W (bool) : Boolean that when true will only display Forex Factory News drawings of the current week.
X (string) : String that gives direction on what lines to plot based on Time (options= "Future", "Both").
Returns: void
newTable(P, B)
Creates a new Table object with parameters tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
B (color) : Border and frame color for the News Table.
Returns: Empty Forex Factory News Table.
resetTable(P, S, headTextC, headBgC, B)
Resets a Table object with parameters and headers tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
B (color) : Border and frame color for the News Table.
Returns: Empty Forex Factory News Table.
logNews(N, TBL, R, S, rowTextC, rowBgC)
Adds an event to the Forex Factory News Table.
Parameters:
N (News) : News-type object.
TBL (table) : Forex Factory News Table object to add the News to.
R (int) : Row to add the event to in the Forex Factory News Table.
S (string) : Size string for the event's text, in Pine Script v5 format.
rowTextC (color)
rowBgC (color)
Returns: void
FF_Table(N, P, S, headTextC, headBgC, rowTextC, rowBgC, B)
Creates the Forex Factory News Table.
Parameters:
N (array) : News-type array containing all the Forex Factory News.
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
rowTextC (color)
rowBgC (color)
B (color) : Border and frame color for the News Table.
Returns: Forex Factory News Table.
timeline(N, T, F, TZH, TZM, D)
Shades Forex Factory News events in the Forex Factory News Table after they occur.
Parameters:
N (array) : News-type array containing all the Forex Factory News.
T (table) : Forex Facory News table object.
F (color) : Color used as shading once the Forex Factory News has occurred.
TZH (int) : Custom Timezone hour, if any.
TZM (int) : Custom Timezone minute, if any.
D (bool) : Daily Forex Factory News flag.
Returns: Forex Factory News Table.
News
Custom News type which contains informatino about a Forex Factory News Event.
Fields:
dow (series string) : Day of the week, in DDD format (i.e. 'Mon').
dat (series string) : Date, in MMM D format (i.e. 'Jan 1').
_t (series int)
tod (series string) : Time of the day, in hh:mm 24-Hour format (i.e 17:10).
cur (series string) : Currency, in CCC format (i.e. "USD").
imp (series color) : Impact, the respective impact color for Forex Factory News Events.
ttl (series string) : Title, encoded in a custom number mapping (see the toodegrees/toodegrees_forex_factory library to learn more).
tmst (series int)
ln (series line)
AuthLibLibrary "AuthLib"
DrawingData
Fields:
kzone1Boxes (array)
kzone2Boxes (array)
kzone3Boxes (array)
kzone4Boxes (array)
kzone5Boxes (array)
kzone6Boxes (array)
kzone1Labels (array)
kzone2Labels (array)
kzone3Labels (array)
kzone4Labels (array)
kzone5Labels (array)
kzone6Labels (array)
kzone1TrendLines (array)
kzone2TrendLines (array)
kzone3TrendLines (array)
kzone4TrendLines (array)
kzone5TrendLines (array)
kzone6TrendLines (array)
kzone1PriceLabels (array)
kzone2PriceLabels (array)
kzone3PriceLabels (array)
kzone4PriceLabels (array)
kzone5PriceLabels (array)
kzone6PriceLabels (array)
SITFX_FuturesSpec_v17SITFX_FuturesSpec_v17 – Universal Futures Contract Library
Full-scale futures contract specification library for Pine Script v6. Covers CME, CBOT, NYMEX, COMEX, CFE, Eurex, ICE, and more – including minis, micros, metals, energies, FX, and bonds.
Key Features:
✅ Instrument‑agnostic: ES/MES, NQ/MNQ, YM/MYM, RTY/M2K, metals, energies, FX, bonds
✅ Full contract data: Tick size, tick value, point value, margins
✅ Continuation‑safe: Single‑line logic, no arrays or continuation errors
✅ Foundation for SITFX tools: Gann, Fibs, structure, and risk modules
Usage example:
import SITFX_FuturesSpec_v17/1 as fs
spec = fs.get(syminfo.root)
label.new(bar_index, high, str.format("{0}: Tick={1}, Value=${2}", spec.name, spec.tickSize, spec.tickValue))
BarUtils: Get Bar Index from DateLibrary "BarUtils"
getBarIndexFromDate(targetTimestamp)
Parameters:
targetTimestamp (int)
**Description**:
This utility provides a reliable way to calculate the `bar_index` of a specific calendar date, regardless of chart resolution. It's especially useful for anchoring scripts to historical events, labeling macroeconomic moments, or marking custom time-based signals that must remain consistent across timeframes.
Unlike hardcoded `bar_index - N` approaches, this function dynamically estimates the number of bars between a given `timestamp()` and the current bar using the actual time-per-bar (`time - time `). It works correctly on intraday, daily, weekly, and monthly charts.
### 💡 **Function Provided**:
import TradeTitan120/BarUtils/1
* `getBarIndexFromDate(int targetTimestamp)`
→ Returns the estimated `bar_index` that aligns with a given timestamp
### ✅ **Use Cases**:
* Marking past events like FOMC meetings, market crashes, or personal signals
* Backtesting entry/exit conditions from specific calendar dates
* Anchoring visual elements (shapes, lines, labels) across resolutions
This tool is simple, fast, and built for accuracy. Use it to enhance multi-timeframe compatibility in any script.
hudDisplay_v1Library "hudDisplay_v1"
f_getPosition(loc)
Parameters:
loc (string)
f_getTableSize(layout, itemCount)
Parameters:
layout (string)
itemCount (int)
f_getCellPosition(layout, index)
Parameters:
layout (string)
index (int)
f_drawHUD(show, loc, layout, content, textColor, bgColor)
Parameters:
show (bool)
loc (string)
layout (string)
content (array)
textColor (color)
bgColor (color)
TextLibrary "Text"
library to format text in different fonts or cases plus a sort function.
🔸 Credits and Usage
This library is inspired by the work of three authors (in chronological order of publication date):
Unicode font function - JD - Duyck
UnicodeReplacementFunction - wlhm
font - kaigouthro
🔹 Fonts
Besides extra added font options, the toFont(fromText, font) method uses a different technique. On the first runtime bar (whether it is barstate.isfirst , barstate.islast , or between) regular letters and numbers and mapped with the chosen font. After this, each character is replaced using the build-in key - value pair map function .
Also an enum Efont is included.
Note: Some fonts are not complete, for example there isn't a replacement for every character in Superscript/Subscript.
Example of usage (besides the included table example):
import fikira/Text/1 as t
i_font = input.enum(t.Efont.Blocks)
if barstate.islast
sentence = "this sentence contains words"
label.new(bar_index, 0, t.toFont(fromText = sentence, font = str.tostring(i_font)), style=label.style_label_lower_right)
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Circled" ), style=label.style_label_lower_left )
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Wiggly" ), style=label.style_label_upper_right)
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Upside Latin" ), style=label.style_label_upper_left )
🔹 Cases
The script includes a toCase(fromText, case) method to transform text into snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase, as well as an enum Ecase .
Example of usage (besides the included table example):
import fikira/Text/1 as t
i_case = input.enum(t.Ecase.camel)
if barstate.islast
sentence = "this sentence contains words"
label.new(bar_index, 0, t.toCase(fromText = sentence, case = str.tostring(i_case)), style=label.style_label_lower_right)
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "snake_case" ), style=label.style_label_lower_left )
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "PascalCase" ), style=label.style_label_upper_right)
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "SNAKE_CASE" ), style=label.style_label_upper_left )
🔹 Sort
The sort(strings, order, sortByUnicodeDecimalNumbers) method returns a sorted array of strings.
strings: array of strings, for example words = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord")
order: "asc" / "desc" (ascending / descending)
sortByUnicodeDecimalNumbers: true/false; default = false
_____
• sortByUnicodeDecimalNumbers: every Unicode character is linked to a Unicode Decimal number ( wikipedia.org/wiki/List_of_Unicode_characters ), for example:
1 49
2 50
3 51
...
A 65
B 66
...
S 83
...
_ 95
` 96
a 97
b 98
...
o 111
p 112
q 113
r 114
s 115
...
This means, if we sort without adjusting ( sortByUnicodeDecimalNumbers = true ), in ascending order, the letter b (98 - small) would be after S (83 - Capital).
By disabling sortByUnicodeDecimalNumbers , Capital letters are intermediate transformed to str.lower() after which the Unicode Decimal number is retrieved from the small number instead of the capital number. For example S (83) -> s (115), after which the number 115 is used to sort instead of 83.
Example of usage (besides the included table example):
import fikira/Text/1 as t
if barstate.islast
aWords = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord")
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_right)
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_left )
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_right)
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_left )
🔸 Methods/functions
method toFont(fromText, font)
toFont : Transforms text into the selected font
Namespace types: series string, simple string, input string, const string
Parameters:
fromText (string)
font (string)
Returns: `fromText` transformed to desired `font`
method toCase(fromText, case)
toCase : formats text to snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase
Namespace types: series string, simple string, input string, const string
Parameters:
fromText (string)
case (string)
Returns: `fromText` formatted to desired `case`
method sort(strings, order, sortByUnicodeDecimalNumbers)
sort : sorts an array of strings, ascending/descending and by Unicode Decimal numbers or not.
Namespace types: array
Parameters:
strings (array)
order (string)
sortByUnicodeDecimalNumbers (bool)
Returns: Sorted array of strings
SIC_TICKER_DATAThe SIC Ticker Data is an advanced and efficient library for ticker-to-industry classification and sector analysis. Built with enterprise-grade performance optimizations, this library provides instant access to SIC codes, industry classifications, and peer company data for comprehensive market analysis.
Perfect for: Sector rotation strategies, peer analysis, portfolio diversification, market screening, and financial research tools.
The simple idea behind this library is to pull any data related to SIC number of any US stock market ticker provided by SEC in order to see the industry and also see the exact competitors of the ticker.
The library stores 3 types of data: SIC number, Ticker, and Industry name. What makes it very useful is that you can pull any one of this data using the other. For example, if you would like to know which tickers are inside a certain SIC, or what's the SIC number of a specific ticker, or even which tickers are inside a certain industry, you can use this library to pull this data. The idea for data inside this library is to be accessible in any direction possible as long as they're related to each other.
We've also published a simple indicator that uses this library in order to demonstrate the inner workings of this library.
The library stores thousands of tickers and their relevant SIC code and industry for your use and is constantly updated with new data when available. This is a large library but it is optimized to run as fast as possible. The previous unpublished versions would take over 40 seconds to load any data but the final public version here loads the data in less than 5 seconds.
🔍 Primary Lookup Functions
createDataStore()
Initialize the library with all pre-loaded data.
store = data.createDataStore()
getSicByTicker(store, ticker)
Get SIC code for any ticker symbol.
sic = data.getSicByTicker(store, "AAPL") // Returns: "3571"
getIndustryByTicker(store, ticker)
Get industry classification for any ticker.
industry = data.getIndustryByTicker(store, "AAPL") // Returns: "Computer Hardware"
getTickersBySic(store, sic)
Get all companies in a specific SIC code.
software = data.getTickersBySic(store, "7372") // Returns: "MSFT,GOOGL,META,V,MA,CRM,ADBE,ORCL,NOW,INTU"
getTickersByIndustry(store, industry)
Get all companies in an industry.
retail = data.getTickersByIndustry(store, "Retail") // Returns: "AMZN,HD,WMT,TGT,COST,LOW"
📊 Array & Analysis Functions
getTickerArrayBySic(store, sic)
Get tickers as array for processing.
techArray = data.getTickerArrayBySic(store, "7372")
for i = 0 to array.size(techArray) - 1
ticker = array.get(techArray, i)
// Process each tech company
getTickerCountBySic(store, sic)
Count companies in a sector (ultra-fast).
pinescripttechCount = data.getTickerCountBySic(store, "7372") // Returns: 10
🎯 Utility Functions
tickerExists(store, ticker)
Check if ticker exists in database.
exists = data.tickerExists(store, "AAPL") // Returns: true
tickerInSic(store, ticker, sic)
Check if ticker belongs to specific sector.
isInTech = data.tickerInSic(store, "AAPL", "3571") // Returns: true
💡 Usage Examples
Example 1: Basic Ticker Lookup
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Ticker Analysis", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
currentIndustry = data.getIndustryByTicker(store, syminfo.ticker)
if barstate.islast and currentSic != "NOT_FOUND"
label.new(bar_index, high, syminfo.ticker + " SIC: " + currentSic + " Industry: " + currentIndustry)
Example 2: Sector Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Sector Comparison", overlay=false)
store = data.createDataStore()
// Compare sector sizes
techCount = data.getTickerCountBySic(store, "7372") // Software
financeCount = data.getTickerCountBySic(store, "6199") // Finance
healthCount = data.getTickerCountBySic(store, "2834") // Pharmaceutical
plot(techCount, title="Tech Companies", color=color.blue)
plot(financeCount, title="Finance Companies", color=color.green)
plot(healthCount, title="Health Companies", color=color.red)
Example 3: Peer Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Find Competitors", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
if currentSic != "NOT_FOUND"
competitors = data.getTickersBySic(store, currentSic)
peerCount = data.getTickerCountBySic(store, currentSic)
if barstate.islast
label.new(bar_index, high, "Competitors (" + str.tostring(peerCount) + "): " + competitors)
Example 4: Portfolio Sector Allocation
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Portfolio Analysis", overlay=false)
store = data.createDataStore()
// Analyze your portfolio's sector distribution
portfolioTickers = array.from("AAPL", "MSFT", "GOOGL", "JPM", "JNJ")
sectorCount = map.new()
for i = 0 to array.size(portfolioTickers) - 1
ticker = array.get(portfolioTickers, i)
industry = data.getIndustryByTicker(store, ticker)
if industry != "NOT_FOUND"
currentCount = map.get(sectorCount, industry)
newCount = na(currentCount) ? 1 : currentCount + 1
map.put(sectorCount, industry, newCount)
🔧 Advanced Feature
You can also bulk load data for large data sets like this:
// Pre-format your data as pipe-separated string
bulkData = "AAPL:3571:Computer Hardware|MSFT:7372:Software|GOOGL:7372:Software"
store = data.createDataStoreFromBulk(bulkData)
fibpointLibrary "fibpoint"
A library for generating Fibonacci retracement levels on a chart, including customizable lines, labels, and filled areas between levels. It provides functionality to plot Fibonacci levels based on given price points and bar indices, with options for custom levels and colors.
getFib(startPoint, endPoint, startIdx, endIdx, fibLevels, fibColors, tsp)
Calculates Fibonacci retracement levels between two price points and draws corresponding lines and labels on the chart.
Parameters:
startPoint (float) : The starting price point for the Fibonacci retracement.
endPoint (float) : The ending price point for the Fibonacci retracement.
startIdx (int) : The bar index where the Fibonacci retracement starts.
endIdx (int) : The bar index where the Fibonacci retracement ends.
fibLevels (array) : An optional array of custom Fibonacci levels (default is ).
fibColors (array) : An optional array of colors for each Fibonacci level (default is a predefined color array).
tsp (int) : The transparency level for the fill between Fibonacci levels (default is 90).
Returns: A tuple containing an array of fibItem objects (each with a line and label) and an array of linefill objects for the filled areas between levels.
fibItem
A custom type representing a Fibonacci level with its associated line and label.
Fields:
line (series line) : The line object drawn for the Fibonacci level.
label (series label) : The label object displaying the Fibonacci level value.
TimeframeInputToStringMaps a worded string for timeframes useful when working with the input.timeframe settings input. Use like timeframeToString("120") and the output will be "2 hour"
Color█ OVERVIEW
This library is a Pine Script® programming tool for advanced color processing. It provides a comprehensive set of functions for specifying and analyzing colors in various color spaces, mixing and manipulating colors, calculating custom gradients and schemes, detecting contrast, and converting colors to or from hexadecimal strings.
█ CONCEPTS
Color
Color refers to how we interpret light of different wavelengths in the visible spectrum . The colors we see from an object represent the light wavelengths that it reflects, emits, or transmits toward our eyes. Some colors, such as blue and red, correspond directly to parts of the spectrum. Others, such as magenta, arise from a combination of wavelengths to which our minds assign a single color.
The human interpretation of color lends itself to many uses in our world. In the context of financial data analysis, the effective use of color helps transform raw data into insights that users can understand at a glance. For example, colors can categorize series, signal market conditions and sessions, and emphasize patterns or relationships in data.
Color models and spaces
A color model is a general mathematical framework that describes colors using sets of numbers. A color space is an implementation of a specific color model that defines an exact range (gamut) of reproducible colors based on a set of primary colors , a reference white point , and sometimes additional parameters such as viewing conditions.
There are numerous different color spaces — each describing the characteristics of color in unique ways. Different spaces carry different advantages, depending on the application. Below, we provide a brief overview of the concepts underlying the color spaces supported by this library.
RGB
RGB is one of the most well-known color models. It represents color as an additive mixture of three primary colors — red, green, and blue lights — with various intensities. Each cone cell in the human eye responds more strongly to one of the three primaries, and the average person interprets the combination of these lights as a distinct color (e.g., pure red + pure green = yellow).
The sRGB color space is the most common RGB implementation. Developed by HP and Microsoft in the 1990s, sRGB provided a standardized baseline for representing color across CRT monitors of the era, which produced brightness levels that did not increase linearly with the input signal. To match displays and optimize brightness encoding for human sensitivity, sRGB applied a nonlinear transformation to linear RGB signals, often referred to as gamma correction . The result produced more visually pleasing outputs while maintaining a simple encoding. As such, sRGB quickly became a standard for digital color representation across devices and the web. To this day, it remains the default color space for most web-based content.
TradingView charts and Pine Script `color.*` built-ins process color data in sRGB. The red, green, and blue channels range from 0 to 255, where 0 represents no intensity, and 255 represents maximum intensity. Each combination of red, green, and blue values represents a distinct color, resulting in a total of 16,777,216 displayable colors.
CIE XYZ and xyY
The XYZ color space, developed by the International Commission on Illumination (CIE) in 1931, aims to describe all color sensations that a typical human can perceive. It is a cornerstone of color science, forming the basis for many color spaces used today. XYZ, and the derived xyY space, provide a universal representation of color that is not tethered to a particular display. Many widely used color spaces, including sRGB, are defined relative to XYZ or derived from it.
The CIE built the color space based on a series of experiments in which people matched colors they perceived from mixtures of lights. From these experiments, the CIE developed color-matching functions to calculate three components — X, Y, and Z — which together aim to describe a standard observer's response to visible light. X represents a weighted response to light across the color spectrum, with the highest contribution from long wavelengths (e.g., red). Y represents a weighted response to medium wavelengths (e.g., green), and it corresponds to a color's relative luminance (i.e., brightness). Z represents a weighted response to short wavelengths (e.g., blue).
From the XYZ space, the CIE developed the xyY chromaticity space, which separates a color's chromaticity (hue and colorfulness) from luminance. The CIE used this space to define the CIE 1931 chromaticity diagram , which represents the full range of visible colors at a given luminance. In color science and lighting design, xyY is a common means for specifying colors and visualizing the supported ranges of other color spaces.
CIELAB and Oklab
The CIELAB (L*a*b*) color space, derived from XYZ by the CIE in 1976, expresses colors based on opponent process theory. The L* component represents perceived lightness, and the a* and b* components represent the balance between opposing unique colors. The a* value specifies the balance between green and red , and the b* value specifies the balance between blue and yellow .
The primary intention of CIELAB was to provide a perceptually uniform color space, where fixed-size steps through the space correspond to uniform perceived changes in color. Although relatively uniform, the color space has been found to exhibit some non-uniformities, particularly in the blue part of the color spectrum. Regardless, modern applications often use CIELAB to estimate perceived color differences and calculate smooth color gradients.
In 2020, a new LAB-oriented color space, Oklab , was introduced by Björn Ottosson as an attempt to rectify the non-uniformities of other perceptual color spaces. Similar to CIELAB, the L value in Oklab represents perceived lightness, and the a and b values represent the balance between opposing unique colors. Oklab has gained widespread adoption as a perceptual space for color processing, with support in the latest CSS Color specifications and many software applications.
Cylindrical models
A cylindrical-coordinate model transforms an underlying color model, such as RGB or LAB, into an alternative expression of color information that is often more intuitive for the average person to use and understand.
Instead of a mixture of primary colors or opponent pairs, these models represent color as a hue angle on a color wheel , with additional parameters that describe other qualities such as lightness and colorfulness (a general term for concepts like chroma and saturation). In cylindrical-coordinate spaces, users can select a color and modify its lightness or other qualities without altering the hue.
The three most common RGB-based models are HSL (Hue, Saturation, Lightness), HSV (Hue, Saturation, Value), and HWB (Hue, Whiteness, Blackness). All three define hue angles in the same way, but they define colorfulness and lightness differently. Although they are not perceptually uniform, HSL and HSV are commonplace in color pickers and gradients.
For CIELAB and Oklab, the cylindrical-coordinate versions are CIELCh and Oklch , which express color in terms of perceived lightness, chroma, and hue. They offer perceptually uniform alternatives to RGB-based models. These spaces create unique color wheels, and they have more strict definitions of lightness and colorfulness. Oklch is particularly well-suited for generating smooth, perceptual color gradients.
Alpha and transparency
Many color encoding schemes include an alpha channel, representing opacity . Alpha does not help define a color in a color space; it determines how a color interacts with other colors in the display. Opaque colors appear with full intensity on the screen, whereas translucent (semi-opaque) colors blend into the background. Colors with zero opacity are invisible.
In Pine Script, there are two ways to specify a color's alpha:
• Using the `transp` parameter of the built-in `color.*()` functions. The specified value represents transparency (the opposite of opacity), which the functions translate into an alpha value.
• Using eight-digit hexadecimal color codes. The last two digits in the code represent alpha directly.
A process called alpha compositing simulates translucent colors in a display. It creates a single displayed color by mixing the RGB channels of two colors (foreground and background) based on alpha values, giving the illusion of a semi-opaque color placed over another color. For example, a red color with 80% transparency on a black background produces a dark shade of red.
Hexadecimal color codes
A hexadecimal color code (hex code) is a compact representation of an RGB color. It encodes a color's red, green, and blue values into a sequence of hexadecimal ( base-16 ) digits. The digits are numerals ranging from `0` to `9` or letters from `a` (for 10) to `f` (for 15). Each set of two digits represents an RGB channel ranging from `00` (for 0) to `ff` (for 255).
Pine scripts can natively define colors using hex codes in the format `#rrggbbaa`. The first set of two digits represents red, the second represents green, and the third represents blue. The fourth set represents alpha . If unspecified, the value is `ff` (fully opaque). For example, `#ff8b00` and `#ff8b00ff` represent an opaque orange color. The code `#ff8b0033` represents the same color with 80% transparency.
Gradients
A color gradient maps colors to numbers over a given range. Most color gradients represent a continuous path in a specific color space, where each number corresponds to a mix between a starting color and a stopping color. In Pine, coders often use gradients to visualize value intensities in plots and heatmaps, or to add visual depth to fills.
The behavior of a color gradient depends on the mixing method and the chosen color space. Gradients in sRGB usually mix along a straight line between the red, green, and blue coordinates of two colors. In cylindrical spaces such as HSL, a gradient often rotates the hue angle through the color wheel, resulting in more pronounced color transitions.
Color schemes
A color scheme refers to a set of colors for use in aesthetic or functional design. A color scheme usually consists of just a few distinct colors. However, depending on the purpose, a scheme can include many colors.
A user might choose palettes for a color scheme arbitrarily, or generate them algorithmically. There are many techniques for calculating color schemes. A few simple, practical methods are:
• Sampling a set of distinct colors from a color gradient.
• Generating monochromatic variants of a color (i.e., tints, tones, or shades with matching hues).
• Computing color harmonies — such as complements, analogous colors, triads, and tetrads — from a base color.
This library includes functions for all three of these techniques. See below for details.
█ CALCULATIONS AND USE
Hex string conversion
The `getHexString()` function returns a string containing the eight-digit hexadecimal code corresponding to a "color" value or set of sRGB and transparency values. For example, `getHexString(255, 0, 0)` returns the string `"#ff0000ff"`, and `getHexString(color.new(color.red, 80))` returns `"#f2364533"`.
The `hexStringToColor()` function returns the "color" value represented by a string containing a six- or eight-digit hex code. The `hexStringToRGB()` function returns a tuple containing the sRGB and transparency values. For example, `hexStringToColor("#f23645")` returns the same value as color.red .
Programmers can use these functions to parse colors from "string" inputs, perform string-based color calculations, and inspect color data in text outputs such as Pine Logs and tables.
Color space conversion
All other `get*()` functions convert a "color" value or set of sRGB channels into coordinates in a specific color space, with transparency information included. For example, the tuple returned by `getHSL()` includes the color's hue, saturation, lightness, and transparency values.
To convert data from a color space back to colors or sRGB and transparency values, use the corresponding `*toColor()` or `*toRGB()` functions for that space (e.g., `hslToColor()` and `hslToRGB()`).
Programmers can use these conversion functions to process inputs that define colors in different ways, perform advanced color manipulation, design custom gradients, and more.
The color spaces this library supports are:
• sRGB
• Linear RGB (RGB without gamma correction)
• HSL, HSV, and HWB
• CIE XYZ and xyY
• CIELAB and CIELCh
• Oklab and Oklch
Contrast-based calculations
Contrast refers to the difference in luminance or color that makes one color visible against another. This library features two functions for calculating luminance-based contrast and detecting themes.
The `contrastRatio()` function calculates the contrast between two "color" values based on their relative luminance (the Y value from CIE XYZ) using the formula from version 2 of the Web Content Accessibility Guidelines (WCAG) . This function is useful for identifying colors that provide a sufficient brightness difference for legibility.
The `isLightTheme()` function determines whether a specified background color represents a light theme based on its contrast with black and white. Programmers can use this function to define conditional logic that responds differently to light and dark themes.
Color manipulation and harmonies
The `negative()` function calculates the negative (i.e., inverse) of a color by reversing the color's coordinates in either the sRGB or linear RGB color space. This function is useful for calculating high-contrast colors.
The `grayscale()` function calculates a grayscale form of a specified color with the same relative luminance.
The functions `complement()`, `splitComplements()`, `analogousColors()`, `triadicColors()`, `tetradicColors()`, `pentadicColors()`, and `hexadicColors()` calculate color harmonies from a specified source color within a given color space (HSL, CIELCh, or Oklch). The returned harmonious colors represent specific hue rotations around a color wheel formed by the chosen space, with the same defined lightness, saturation or chroma, and transparency.
Color mixing and gradient creation
The `add()` function simulates combining lights of two different colors by additively mixing their linear red, green, and blue components, ignoring transparency by default. Users can calculate a transparency-weighted mixture by setting the `transpWeight` argument to `true`.
The `overlay()` function estimates the color displayed on a TradingView chart when a specific foreground color is over a background color. This function aids in simulating stacked colors and analyzing the effects of transparency.
The `fromGradient()` and `fromMultiStepGradient()` functions calculate colors from gradients in any of the supported color spaces, providing flexible alternatives to the RGB-based color.from_gradient() function. The `fromGradient()` function calculates a color from a single gradient. The `fromMultiStepGradient()` function calculates a color from a piecewise gradient with multiple defined steps. Gradients are useful for heatmaps and for coloring plots or drawings based on value intensities.
Scheme creation
Three functions in this library calculate palettes for custom color schemes. Scripts can use these functions to create responsive color schemes that adjust to calculated values and user inputs.
The `gradientPalette()` function creates an array of colors by sampling a specified number of colors along a gradient from a base color to a target color, in fixed-size steps.
The `monoPalette()` function creates an array containing monochromatic variants (tints, tones, or shades) of a specified base color. Whether the function mixes the color toward white (for tints), a form of gray (for tones), or black (for shades) depends on the `grayLuminance` value. If unspecified, the function automatically chooses the mix behavior with the highest contrast.
The `harmonyPalette()` function creates a matrix of colors. The first column contains the base color and specified harmonies, e.g., triadic colors. The columns that follow contain tints, tones, or shades of the harmonic colors for additional color choices, similar to `monoPalette()`.
█ EXAMPLE CODE
The example code at the end of the script generates and visualizes color schemes by processing user inputs. The code builds the scheme's palette based on the "Base color" input and the additional inputs in the "Settings/Inputs" tab:
• "Palette type" specifies whether the palette uses a custom gradient, monochromatic base color variants, or color harmonies with monochromatic variants.
• "Target color" sets the top color for the "Gradient" palette type.
• The "Gray luminance" inputs determine variation behavior for "Monochromatic" and "Harmony" palette types. If "Auto" is selected, the palette mixes the base color toward white or black based on its brightness. Otherwise, it mixes the color toward the grayscale color with the specified relative luminance (from 0 to 1).
• "Harmony type" specifies the color harmony used in the palette. Each row in the palette corresponds to one of the harmonious colors, starting with the base color.
The code creates a table on the first bar to display the collection of calculated colors. Each cell in the table shows the color's `getHexString()` value in a tooltip for simple inspection.
Look first. Then leap.
█ EXPORTED FUNCTIONS
Below is a complete list of the functions and overloads exported by this library.
getRGB(source)
Retrieves the sRGB red, green, blue, and transparency components of a "color" value.
getHexString(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channel values to a string representing the corresponding color's hexadecimal form.
getHexString(source)
(Overload 2 of 2) Converts a "color" value to a string representing the sRGB color's hexadecimal form.
hexStringToRGB(source)
Converts a string representing an sRGB color's hexadecimal form to a set of decimal channel values.
hexStringToColor(source)
Converts a string representing an sRGB color's hexadecimal form to a "color" value.
getLRGB(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channel values to a set of linear RGB values with specified transparency information.
getLRGB(source)
(Overload 2 of 2) Retrieves linear RGB channel values and transparency information from a "color" value.
lrgbToRGB(lr, lg, lb, t)
Converts a set of linear RGB channel values to a set of sRGB values with specified transparency information.
lrgbToColor(lr, lg, lb, t)
Converts a set of linear RGB channel values and transparency information to a "color" value.
getHSL(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of HSL values with specified transparency information.
getHSL(source)
(Overload 2 of 2) Retrieves HSL channel values and transparency information from a "color" value.
hslToRGB(h, s, l, t)
Converts a set of HSL channel values to a set of sRGB values with specified transparency information.
hslToColor(h, s, l, t)
Converts a set of HSL channel values and transparency information to a "color" value.
getHSV(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of HSV values with specified transparency information.
getHSV(source)
(Overload 2 of 2) Retrieves HSV channel values and transparency information from a "color" value.
hsvToRGB(h, s, v, t)
Converts a set of HSV channel values to a set of sRGB values with specified transparency information.
hsvToColor(h, s, v, t)
Converts a set of HSV channel values and transparency information to a "color" value.
getHWB(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of HWB values with specified transparency information.
getHWB(source)
(Overload 2 of 2) Retrieves HWB channel values and transparency information from a "color" value.
hwbToRGB(h, w, b, t)
Converts a set of HWB channel values to a set of sRGB values with specified transparency information.
hwbToColor(h, w, b, t)
Converts a set of HWB channel values and transparency information to a "color" value.
getXYZ(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of XYZ values with specified transparency information.
getXYZ(source)
(Overload 2 of 2) Retrieves XYZ channel values and transparency information from a "color" value.
xyzToRGB(x, y, z, t)
Converts a set of XYZ channel values to a set of sRGB values with specified transparency information
xyzToColor(x, y, z, t)
Converts a set of XYZ channel values and transparency information to a "color" value.
getXYY(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of xyY values with specified transparency information.
getXYY(source)
(Overload 2 of 2) Retrieves xyY channel values and transparency information from a "color" value.
xyyToRGB(xc, yc, y, t)
Converts a set of xyY channel values to a set of sRGB values with specified transparency information.
xyyToColor(xc, yc, y, t)
Converts a set of xyY channel values and transparency information to a "color" value.
getLAB(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of CIELAB values with specified transparency information.
getLAB(source)
(Overload 2 of 2) Retrieves CIELAB channel values and transparency information from a "color" value.
labToRGB(l, a, b, t)
Converts a set of CIELAB channel values to a set of sRGB values with specified transparency information.
labToColor(l, a, b, t)
Converts a set of CIELAB channel values and transparency information to a "color" value.
getOKLAB(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of Oklab values with specified transparency information.
getOKLAB(source)
(Overload 2 of 2) Retrieves Oklab channel values and transparency information from a "color" value.
oklabToRGB(l, a, b, t)
Converts a set of Oklab channel values to a set of sRGB values with specified transparency information.
oklabToColor(l, a, b, t)
Converts a set of Oklab channel values and transparency information to a "color" value.
getLCH(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of CIELCh values with specified transparency information.
getLCH(source)
(Overload 2 of 2) Retrieves CIELCh channel values and transparency information from a "color" value.
lchToRGB(l, c, h, t)
Converts a set of CIELCh channel values to a set of sRGB values with specified transparency information.
lchToColor(l, c, h, t)
Converts a set of CIELCh channel values and transparency information to a "color" value.
getOKLCH(r, g, b, t)
(Overload 1 of 2) Converts a set of sRGB channels to a set of Oklch values with specified transparency information.
getOKLCH(source)
(Overload 2 of 2) Retrieves Oklch channel values and transparency information from a "color" value.
oklchToRGB(l, c, h, t)
Converts a set of Oklch channel values to a set of sRGB values with specified transparency information.
oklchToColor(l, c, h, t)
Converts a set of Oklch channel values and transparency information to a "color" value.
contrastRatio(value1, value2)
Calculates the contrast ratio between two colors values based on the formula from version 2 of the Web Content Accessibility Guidelines (WCAG).
isLightTheme(source)
Detects whether a background color represents a light theme or dark theme, based on the amount of contrast between the color and the white and black points.
grayscale(source)
Calculates the grayscale version of a color with the same relative luminance (i.e., brightness).
negative(source, colorSpace)
Calculates the negative (i.e., inverted) form of a specified color.
complement(source, colorSpace)
Calculates the complementary color for a `source` color using a cylindrical color space.
analogousColors(source, colorSpace)
Calculates the analogous colors for a `source` color using a cylindrical color space.
splitComplements(source, colorSpace)
Calculates the split-complementary colors for a `source` color using a cylindrical color space.
triadicColors(source, colorSpace)
Calculates the two triadic colors for a `source` color using a cylindrical color space.
tetradicColors(source, colorSpace, square)
Calculates the three square or rectangular tetradic colors for a `source` color using a cylindrical color space.
pentadicColors(source, colorSpace)
Calculates the four pentadic colors for a `source` color using a cylindrical color space.
hexadicColors(source, colorSpace)
Calculates the five hexadic colors for a `source` color using a cylindrical color space.
add(value1, value2, transpWeight)
Additively mixes two "color" values, with optional transparency weighting.
overlay(fg, bg)
Estimates the resulting color that appears on the chart when placing one color over another.
fromGradient(value, bottomValue, topValue, bottomColor, topColor, colorSpace)
Calculates the gradient color that corresponds to a specific value based on a defined value range and color space.
fromMultiStepGradient(value, steps, colors, colorSpace)
Calculates a multi-step gradient color that corresponds to a specific value based on an array of step points, an array of corresponding colors, and a color space.
gradientPalette(baseColor, stopColor, steps, strength, model)
Generates a palette from a gradient between two base colors.
monoPalette(baseColor, grayLuminance, variations, strength, colorSpace)
Generates a monochromatic palette from a specified base color.
harmonyPalette(baseColor, harmonyType, grayLuminance, variations, strength, colorSpace)
Generates a palette consisting of harmonious base colors and their monochromatic variants.
LabelManagementLabel management with fluent configuration, change tracking, and named registry
LabelManagement is a Pine Script library for creating and managing dynamic chart labels. Built with a fluent-style API , it simplifies label creation, styling, positioning, and content updates through method chaining and centralized control.
Manage 'sticky' labels easily across bars with expressive, readable code that reduces clutter and improves code clarity.
Example usage:
// Close label – to the right of the last bar
labels.get("close")
.style(label.style_label_left)
.bgColor(color.gray)
.xy(bar_index, close)
.textValue("C: " + str.tostring(close, "#.##"))
.textColor(color.white)
.tooltip("This is the close price")
.apply()
Key features:
Fluent API – Build and update labels using a chainable configuration flow
Named label registry – Access and manage labels by name, e.g., "entry", "stop", "target"
Change tracking – Update only when necessary to reduce redraws
Deferred application – Apply all changes in one efficient operation
Centralized control – Works well in modular or multi-label environments
This library is designed for Pine developers who want more control and less boilerplate when managing visual elements on the chart.
method clone(this)
Creates a new LabelConfig by copying all properties from this instance
Namespace types: LabelConfig
Parameters:
this (LabelConfig) : (LabelConfig) The LabelConfig instance
Returns: (LabelConfig) New LabelConfig instance with identical properties
method applyTo(this, target)
Applies configuration to specified label (required parameter)
Namespace types: LabelConfig
Parameters:
this (LabelConfig) : (LabelConfig) The LabelConfig instance
target (label) : (label) Label to apply config to
Returns: (LabelConfig) Self-reference for method chaining
method update(this, updates)
Creates a new LabelUpdater with change tracking for this label
Namespace types: series label
Parameters:
this (label) : (label) The label instance
updates (LabelConfig) : (LabelConfig) Optional existing config to apply and reuse (if provided, applies to label first)
Returns: (LabelUpdater) New LabelUpdater with blank configs for change tracking
method x(this, value)
Sets the X coordinate with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (int) : (int) New X coordinate
Returns: (LabelUpdater) Self-reference for method chaining
method y(this, value)
Sets the Y coordinate with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (float) : (float) New Y coordinate
Returns: (LabelUpdater) Self-reference for method chaining
method xy(this, x, y)
Sets both X and Y coordinates with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
x (int) : (int) New X coordinate
y (float) : (float) New Y coordinate
Returns: (LabelUpdater) Self-reference for method chaining
method textValue(this, value)
Sets the text content with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New text content
Returns: (LabelUpdater) Self-reference for method chaining
method textColor(this, value)
Sets the text color with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (color) : (color) New text color
Returns: (LabelUpdater) Self-reference for method chaining
method textSize(this, value)
Sets the text size with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New text size
Returns: (LabelUpdater) Self-reference for method chaining
method bgColor(this, value)
Sets the background color with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (color) : (color) New background color
Returns: (LabelUpdater) Self-reference for method chaining
method style(this, value)
Sets the label style with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New style
Returns: (LabelUpdater) Self-reference for method chaining
method yloc(this, value)
Sets the Y location mode with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New yloc
Returns: (LabelUpdater) Self-reference for method chaining
method xloc(this, value)
Sets the X location mode with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New xloc
Returns: (LabelUpdater) Self-reference for method chaining
method tooltip(this, value)
Sets the tooltip content with change tracking (fluent interface)
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New tooltip content
Returns: (LabelUpdater) Self-reference for method chaining
method size(this, value)
Sets the text size with change tracking (fluent interface) - alias for textSize
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
value (string) : (string) New text size
Returns: (LabelUpdater) Self-reference for method chaining
method size(this)
Gets the count of registered labels
Namespace types: LabelManager
Parameters:
this (LabelManager) : (LabelManager) The LabelManager instance
Returns: (int) Number of labels in the registry
method apply(this)
Applies pending changes to linked label and updates tracking
Namespace types: LabelUpdater
Parameters:
this (LabelUpdater) : (LabelUpdater) The LabelUpdater instance
Returns: (LabelUpdater) Self-reference for method chaining
method get(this, name)
Gets or creates a LabelUpdater for the specified name
Namespace types: LabelManager
Parameters:
this (LabelManager) : (LabelManager) The LabelManager instance
name (string) : (string) Unique identifier for the label
Returns: (LabelUpdater) Existing or newly created LabelUpdater for the name
method has(this, name)
Checks if a label with the specified name exists
Namespace types: LabelManager
Parameters:
this (LabelManager) : (LabelManager) The LabelManager instance
name (string) : (string) Name to check for existence
Returns: (bool) True if label exists, false otherwise
method remove(this, name)
Removes a label from the registry and deletes the underlying Pine Script label
Namespace types: LabelManager
Parameters:
this (LabelManager) : (LabelManager) The LabelManager instance
name (string) : (string) Name of the label to remove
Returns: (LabelManager) Self-reference for method chaining
method clear(this)
Removes all labels from registry and deletes all underlying Pine Script labels
Namespace types: LabelManager
Parameters:
this (LabelManager) : (LabelManager) The LabelManager instance
Returns: (LabelManager) Self-reference for method chaining
newManager()
Creates a new LabelManager with empty registry
Returns: (LabelManager) New LabelManager instance ready for use
LabelConfig
LabelConfig Configuration object for label appearance and positioning
Fields:
x (series int) : (series int) X-coordinate (na = unchanged)
y (series float) : (series float) Y-coordinate (na = unchanged)
style (series string) : (series string) Label style (na = unchanged)
yloc (series string) : (series string) Y-location type (na = unchanged)
xloc (series string) : (series string) X-location type (na = unchanged)
bgColor (series color) : (series color) Background color (na = unchanged)
textValue (series string) : (series string) Label text content (na = unchanged)
textSize (series string) : (series string) Text size (na = unchanged)
textColor (series color) : (series color) Text color (na = unchanged)
tooltip (series string) : (series string) Tooltip text (na = unchanged)
LabelUpdater
LabelUpdater Smart label updater with change tracking and minimal updates
Fields:
label (series label) : (label) Reference to the label being updated
latest (LabelConfig) : (LabelConfig) Current known state of the label
updates (LabelConfig) : (LabelConfig) Pending changes to apply
LabelManager
LabelManager Central registry for managing named labels with automatic creation
Fields:
registry (map) : (map) Internal storage mapping names to LabelUpdater instances
juan_dibujosLibrary "juan_dibujos"
extend_line(lineId, labelId)
: Extend specific line with its label
Parameters:
lineId (line)
labelId (label)
update_line_coordinates(lineId, labelId, x1, y1, x2, y2)
: Update specific line coordinates with its label
Parameters:
lineId (line)
labelId (label)
x1 (int)
y1 (float)
x2 (int)
y2 (float)
update_label_coordinates(labelId, value)
: Update coordinates of a label
Parameters:
labelId (label)
value (float)
delete_line(lineId, labelId)
: Delete specific line with its label
Parameters:
lineId (line)
labelId (label)
update_box_coordinates(boxId, labelId, left, top, right, bottom)
: Update specific box coordinates with its label
Parameters:
boxId (box)
labelId (label)
left (int)
top (float)
right (int)
bottom (float)
delete_box(boxId, labelId)
: Delete specific box with its label
Parameters:
boxId (box)
labelId (label)
lib_core_utilsLibrary "lib_core_utils"
Core utility functions for Pine Script strategies
Provides safe mathematical operations, array management, and basic helpers
Version: 1.0.0
Author: NQ Hybrid Strategy Team
Last Updated: 2025-06-18
===================================================================
safe_division(numerator, denominator)
safe_division
@description Performs division with safety checks for zero denominators and invalid values
Parameters:
numerator (float) : (float) The numerator value
denominator (float) : (float) The denominator value
Returns: (float) Result of division, or 0.0 if invalid
safe_division_detailed(numerator, denominator)
safe_division_detailed
@description Enhanced division with detailed result information
Parameters:
numerator (float) : (float) The numerator value
denominator (float) : (float) The denominator value
Returns: (SafeCalculationResult) Detailed calculation result
safe_multiply(a, b)
safe_multiply
@description Performs multiplication with safety checks for overflow and invalid values
Parameters:
a (float) : (float) First multiplier
b (float) : (float) Second multiplier
Returns: (float) Result of multiplication, or 0.0 if invalid
safe_add(a, b)
safe_add
@description Performs addition with safety checks
Parameters:
a (float) : (float) First addend
b (float) : (float) Second addend
Returns: (float) Result of addition, or 0.0 if invalid
safe_subtract(a, b)
safe_subtract
@description Performs subtraction with safety checks
Parameters:
a (float) : (float) Minuend
b (float) : (float) Subtrahend
Returns: (float) Result of subtraction, or 0.0 if invalid
safe_abs(value)
safe_abs
@description Safe absolute value calculation
Parameters:
value (float) : (float) Input value
Returns: (float) Absolute value, or 0.0 if invalid
safe_max(a, b)
safe_max
@description Safe maximum value calculation
Parameters:
a (float) : (float) First value
b (float) : (float) Second value
Returns: (float) Maximum value, handling NA cases
safe_min(a, b)
safe_min
@description Safe minimum value calculation
Parameters:
a (float) : (float) First value
b (float) : (float) Second value
Returns: (float) Minimum value, handling NA cases
safe_array_get(arr, index)
safe_array_get
@description Safely retrieves value from array with bounds checking
Parameters:
arr (array) : (array) The array to access
index (int) : (int) Index to retrieve
Returns: (float) Value at index, or na if invalid
safe_array_push(arr, value, max_size)
safe_array_push
@description Safely pushes value to array with size management
Parameters:
arr (array) : (array) The array to modify
value (float) : (float) Value to push
max_size (int) : (int) Maximum array size
Returns: (bool) True if push was successful
safe_array_unshift(arr, value, max_size)
safe_array_unshift
@description Safely adds value to beginning of array with size management
Parameters:
arr (array) : (array) The array to modify
value (float) : (float) Value to add at beginning
max_size (int) : (int) Maximum array size
Returns: (bool) True if unshift was successful
get_array_stats(arr, max_size)
get_array_stats
@description Gets statistics about an array
Parameters:
arr (array) : (array) The array to analyze
max_size (int) : (int) The maximum allowed size
Returns: (ArrayStats) Statistics about the array
cleanup_array(arr, target_size)
cleanup_array
@description Cleans up array by removing old elements if it's too large
Parameters:
arr (array) : (array) The array to cleanup
target_size (int) : (int) Target size after cleanup
Returns: (int) Number of elements removed
is_valid_price(price)
is_valid_price
@description Checks if a price value is valid for trading calculations
Parameters:
price (float) : (float) Price to validate
Returns: (bool) True if price is valid
is_valid_volume(vol)
is_valid_volume
@description Checks if a volume value is valid
Parameters:
vol (float) : (float) Volume to validate
Returns: (bool) True if volume is valid
sanitize_price(price, default_value)
sanitize_price
@description Sanitizes price value to ensure it's within valid range
Parameters:
price (float) : (float) Price to sanitize
default_value (float) : (float) Default value if price is invalid
Returns: (float) Sanitized price value
sanitize_percentage(pct)
sanitize_percentage
@description Sanitizes percentage value to 0-100 range
Parameters:
pct (float) : (float) Percentage to sanitize
Returns: (float) Sanitized percentage (0-100)
is_session_active(session_string, timezone)
Parameters:
session_string (string)
timezone (string)
get_session_progress(session_string, timezone)
Parameters:
session_string (string)
timezone (string)
format_price(price, decimals)
Parameters:
price (float)
decimals (int)
format_percentage(pct, decimals)
Parameters:
pct (float)
decimals (int)
bool_to_emoji(condition, true_emoji, false_emoji)
Parameters:
condition (bool)
true_emoji (string)
false_emoji (string)
log_debug(message, level)
Parameters:
message (string)
level (string)
benchmark_start()
benchmark_end(start_time)
Parameters:
start_time (int)
get_library_info()
get_library_version()
SafeCalculationResult
SafeCalculationResult
Fields:
value (series float) : (float) The calculated value
is_valid (series bool) : (bool) Whether the calculation was successful
error_message (series string) : (string) Error description if calculation failed
ArrayStats
ArrayStats
Fields:
size (series int) : (int) Current array size
max_size (series int) : (int) Maximum allowed size
is_full (series bool) : (bool) Whether array has reached max capacity
CGMALibrary "CGMA"
This library provides a function to calculate a moving average based on Chebyshev-Gauss Quadrature. This method samples price data more intensely from the beginning and end of the lookback window, giving it a unique character that responds quickly to recent changes while also having a long "memory" of the trend's start. Inspired by reading rohangautam.github.io
What is Chebyshev-Gauss Quadrature?
It's a numerical method to approximate the integral of a function f(x) that is weighted by 1/sqrt(1-x^2) over the interval . The approximation is a simple sum: ∫ f(x)/sqrt(1-x^2) dx ≈ (π/n) * Σ f(xᵢ) where xᵢ are special points called Chebyshev nodes.
How is this applied to a Moving Average?
A moving average can be seen as the "mean value" of the price over a lookback window. The mean value of a function with the Chebyshev weight is calculated as:
Mean = /
The math simplifies beautifully, resulting in the mean being the simple arithmetic average of the function evaluated at the Chebyshev nodes:
Mean = (1/n) * Σ f(xᵢ)
What's unique about this MA?
The Chebyshev nodes xᵢ are not evenly spaced. They are clustered towards the ends of the interval . We map this interval to our lookback period. This means the moving average samples prices more intensely from the beginning and the end of the lookback window, and less intensely from the middle. This gives it a unique character, responding quickly to recent changes while also having a long "memory" of the start of the trend.