Dark & Light Theme [TradingFinder] Switching Colors Library🔵 Introduction
One of the challenges of script users is matching the colors used in indicators or strategies. By default, colors are chosen to display based on either the dark theme or the light theme.
In scripts with a large number of colors used, changing all colors to better display in dark mode or light mode can be a difficult and tedious process.
This library provides developers with the ability to adjust the colors used in their scripts based on the theme of the display.
🔵 Logic
To categorize the color spectrum, the range from 0 to 255 of all three main colors red, green and blue was divided into smaller ranges.
Blue color, which is more effective in darkening or lightening colors, is divided into 8 categories, red color into 5 categories, and green color into 3 categories, because it has little effect on darkening or brightening colors.
The combination of these categories creates 120 different modes for the color range, which leads to a more accurate identification of the color and its brightness, and helps to decide how to change it.
Except for these 120 modes, there are 2 other modes that are related to colors almost white or black, which makes a total of 122 modes.
🔵 How to Use
First, you can add the library to your code as shown in the example below.
import TFlab/Dark_Light_Theme_TradingFinder_Switching_Colors_Library/1 as SC
🟣 Parameters
SwitchingColorMode(Color, Mode) =>
Parameters:
Color (color)
Mode (string)
Color : In this parameter, enter the color you want to adjust based on light mode and dark mode.
Mode : Three modes "Off", "Light" and "Dark" are included in this parameter. "Light" mode is for color adjustment for use in "Light Mode".
"Dark" mode is for color adjustment for use in "Dark Mode" and "Off" mode turns off the color adjustment function and the input color to the function is the same as the output color.
🔵 Function Outputs
OriginalColor = input.color(color.red)
= SC.SwitchingColorMode(OriginalColor, Mode)
指標和策略
VandelayIndicatorLibLibrary "VandelayIndicatorLib"
Art Vandelay's Indicator library
STC_VIL(EEEEEE, BBBB, BBBBB)
Schaff Trend Cycle Calculations
Parameters:
EEEEEE (int) : = Slengt, BBBB = FALenght, BBBBB = SLOLenght
BBBB (simple int)
BBBBB (simple int)
Returns: Long : mAAAAA > mAAAAA - Short : mAAAAA < mAAAAA
stc(source, fast, slow, cycle, d1, d2)
Calculates the value of the Schaff Trend Cycle indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
fast (simple int) : (simple int) Length for the MACD fast smoothing parameter calculation.
slow (simple int) : (simple int) Length for the MACD slow smoothing parameter calculation.
cycle (simple int) : (simple int) Number of bars for the Stochastic values (length).
d1 (simple int) : (simple int) Length for the initial %D smoothing parameter calculation.
d2 (simple int) : (simple int) Length for the final %D smoothing parameter calculation.
Returns: (float) The oscillator value.
ComplexLibrary "Complex"
This library includes user-defined complex type, and functions to perform basic arithmetic operations on complex numbers.
real(radius, angle)
Calculates the real part of a complex number based on its polar coordinates.
Parameters:
radius (float)
angle (float)
imag(radius, angle)
Calculates the imaginary part of a complex number based on its polar coordinates.
Parameters:
radius (float)
angle (float)
rds(real, imag)
Calculates the radius of a complex number based on its cartesian coordinates.
Parameters:
real (float)
imag (float)
ang(real, imag)
Calculates the angle of a complex number based on its cartesian coordinates.
Parameters:
real (float)
imag (float)
method realP(c)
Calculates the real part of a complex number represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
method imagP(c)
Calculates the imaginary part of a complex number represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
method rdsC(c)
Calculates the radius of a complex number represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
method angC(c)
Calculates the angle of a complex number represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
method toCart(c)
Converts a complex number from its polar representation to cartesian.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
method toPolar(c)
Converts a complex number from its cartesian representation to polar.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
method addC(c, z)
Calculates the addition of two complex numbers represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in cartesian coordinates.
z (complex) : Second complex number expressed in cartesian coordinates.
method addP(c, z)
Calculates the addition of two complex numbers represented in polar coordinates. Performing addition and subtraction operations in cartesian form of complex numbers is more efficient.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in polar coordinates.
z (complex) : Second complex number expressed in polar coordinates.
method subC(c, z)
Calculates the subtraction of two complex numbers represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in cartesian coordinates.
z (complex) : Second complex number expressed in cartesian coordinates.
method subP(c, z)
Calculates the subtraction of two complex numbers represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in polar coordinates.
z (complex) : Second complex number expressed in polar coordinates.
method multC(c, z)
Calculates the multiplication of two complex numbers represented in cartesian coordinates. Performing multiplication in polar form of complex numbers is more efficient.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in cartesian coordinates.
z (complex) : Second complex number expressed in cartesian coordinates.
method multP(c, z)
Calculates the multiplication of two complex numbers represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex) : First complex number expressed in polar coordinates.
z (complex) : Second complex number expressed in polar coordinates.
method powC(c, exp, shift)
Exponentiates a complex number represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
exp (float) : The exponent.
shift (float) : The phase shift of the operation. The shift is equal to 2kπ, where k is an integer number from zero to the denominator of the exponent (exclusive). Calculation of the shift value is not included in the function since it isn't always needed and for the purpose of efficiency. Use a for loop to obtain all possible results.
method powP(c, exp, shift)
Exponentiates a complex number represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
exp (float) : The exponent.
shift (float) : The phase shift of the operation. The shift is equal to 2kπ, where k is an integer number from zero to the denominator of the exponent (exclusive). Calculation of the shift value is not included in the function since it isn't always needed and for the purpose of efficiency. Use a for loop to obtain all possible results.
method invC(c)
Calculates the multiplicative inverse of a complex number represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex)
method invP(c)
Calculates the multiplicative inverse of a complex number represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex)
method negC(c)
Negates a complex number represented in cartesian coordinates.
Namespace types: complex
Parameters:
c (complex)
method negP(c)
Negates a complex number represented in polar coordinates.
Namespace types: complex
Parameters:
c (complex)
method con(c)
Calculates the conjugate of a complex number in either forms.
Namespace types: complex
Parameters:
c (complex)
method fAddC(c, d)
Calculates the addition of a complex number represented in cartesian coordinates and a real number.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
d (float)
Returns: The complex number resulted by the addition in cartesian form.
method fAddP(c, d)
Calculates the addition of a complex number represented in polar coordinates and a real number.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
d (float)
Returns: The complex number resulted by the addition in polar form.
method fMultC(c, d)
Calculates the multiplication of a complex number represented in cartesian coordinates and a real number.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in cartesian coordinates.
d (float)
Returns: The complex number resulted by the multiplication in cartesian form.
method fMultP(c, d)
Calculates the multiplication of a complex number represented in polar coordinates and a real number.
Namespace types: complex
Parameters:
c (complex) : A complex number expressed in polar coordinates.
d (float)
Returns: The complex number resulted by the multiplication in polar form.
complex
Complex number expressed in polar or cartesian coordinates.
Fields:
R (series float) : Real part or radius of the complex number.
J (series float) : Imaginary part or angle (phase) of the complex number.
iP (series bool) : This field is employed to keep track of the coordinates of the number. Note that the functions do not verify this field for the purpose of efficiency.
lib_session_gapsLibrary "lib_session_gaps"
simple lib to calculate the gaps between sessions
time_gap()
calculates the time gap between this and previous session (in case of irregular end of previous session, considering extended sessions)
Returns: the time gap between this and previous session in ms (time - time_close )
bar_gap()
calculates the bars missing between this and previous session (in case of irregular end of previous session, considering extended sessions)
Returns: the bars virtually missing between this and previous session (time gap / bar size in ms)
CryptoLibrary "Crypto"
This Library includes functions related to crytocurrencies and their blockchain
btcBlockReward(t)
Delivers the BTC block reward for a specific date/time
Parameters:
t (int) : Time of the current candle
Returns: blockRewardBtc
BinaryLibrary "Binary"
This library includes functions to convert between decimal and binary numeral formats, and logical and arithmetic operations on binary numbers.
method toBin(value)
Converts the provided boolean value into binary integers (0 or 1).
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value (bool) : The boolean value to be converted.
Returns: The converted value in binary integers.
method dec2bin(value, iBits, fBits)
Converts a decimal number into its binary representation.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : The decimal number to be converted.
iBits (int) : The number of binary digits allocated for the integer part.
fBits (int) : The number of binary digits allocated for the fractional part.
Returns: An array containing the binary digits for the integer part at the rightmost positions and the digits for the fractional part at the leftmost positions. The array indexes correspond to the bit positions.
method bin2dec(value, iBits, fBits)
Converts a binary number into its decimal representation.
Namespace types: array
Parameters:
value (array) : The binary number to be converted.
iBits (int) : The number of binary digits allocated for the integer part.
fBits (int) : The number of binary digits allocated for the fractional part.
Returns: The converted value in decimal format.
method lgcAnd(a, b)
Bitwise logical AND of two binary numbers. The result of ANDing two binary digits is 1 only if both digits are 1, otherwise, 0.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
Returns: An array containing the logical AND of the inputs.
method lgcOr(a, b)
Bitwise logical OR of two binary numbers. The result of ORing two binary digits is 0 only if both digits are 0, otherwise, 1.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
Returns: An array containing the logical OR of the inputs.
method lgcXor(a, b)
Bitwise logical XOR of two binary numbers. The result of XORing two binary digits is 1 only if ONE of the digits is 1, otherwise, 0.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
Returns: An array containing the logical XOR of the inputs.
method lgcNand(a, b)
Bitwise logical NAND of two binary numbers. The result of NANDing two binary digits is 0 only if both digits are 1, otherwise, 1.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
Returns: An array containing the logical NAND of the inputs.
method lgcNor(a, b)
Bitwise logical NOR of two binary numbers. The result of NORing two binary digits is 1 only if both digits are 0, otherwise, 0.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
Returns: An array containing the logical NOR of the inputs.
method lgcNot(a)
Bitwise logical NOT of a binary number. The result of NOTing a binary digit is 0 if the digit is 1, or vice versa.
Namespace types: array
Parameters:
a (array) : A binary number.
Returns: An array containing the logical NOT of the input.
method lgc2sC(a)
2's complement of a binary number. The 2's complement of a binary number N with n digits is defined as 2^(n) - N.
Namespace types: array
Parameters:
a (array) : A binary number.
Returns: An array containing the 2's complement of the input.
method shift(value, direction, newBit)
Shifts a binary number in the specified direction by one position.
Namespace types: array
Parameters:
value (array)
direction (int) : The direction of the shift operation.
newBit (int) : The bit to be inserted into the unoccupied slot.
Returns: A tuple of the shifted binary number and the serial output of the shift operation.
method multiShift(value, direction, newBits)
Shifts a binary number in the specified direction by multiple positions.
Namespace types: array
Parameters:
value (array)
direction (int) : The direction of the shift operation.
newBits (array)
Returns: A tuple of the shifted binary number and the serial output of the shift operation.
method crclrShift(value, direction, count)
Circularly shifts a binary number in the specified direction by multiple positions. Each ejected bit is inserted from the opposite side.
Namespace types: array
Parameters:
value (array)
direction (int) : The direction of the shift operation.
count (int) : The number of positions to be shifted by.
Returns: The shifted binary number.
method arithmeticShift(value, direction, count)
Performs arithmetic shift on a binary number in the specified direction by multiple positions. Every new bit is 0 if the shift is leftward, otherwise, it equals the sign bit.
Namespace types: array
Parameters:
value (array)
direction (int) : The direction of the shift operation.
count (int) : The number of positions to be shifted by.
Returns: The shifted binary number.
method add(a, b, carry)
Performs arithmetic addition on two binary numbers.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number.
carry (int) : The input carry of the operation.
Returns: The result of the arithmetic addition of the inputs.
method sub(a, b, carry)
Performs arithmetic subtraction on two binary numbers.
Namespace types: array
Parameters:
a (array) : First binary number.
b (array) : Second binary number. The number to be subtracted.
carry (int) : The input carry of the operation.
Returns: The result of the arithmetic subtraction of the input b from the input a.
ChartUtilsLibrary "ChartUtils"
Library for chart utilities, including managing tables
initTable(rows, cols, bgcolor)
Initializes a table with specific dimensions and color
Parameters:
rows (int) : (int) Number of rows in the table
cols (int) : (int) Number of columns in the table
bgcolor (color) : (color) Background color of the table
Returns: (table) The initialized table
updateTable(tbl, is_price_below_avg, current_investment_USD, strategy_position_size, strategy_position_avg_price, strategy_openprofit, strategy_opentrades, isBullishRate, isBearishRate, mlRSIOverSold, mlRSIOverBought)
Updates the trading table
Parameters:
tbl (table) : (table) The table to update
is_price_below_avg (bool) : (bool) If the current price is below the average price
current_investment_USD (float) : (float) The current investment in USD
strategy_position_size (float) : (float) The size of the current position
strategy_position_avg_price (float) : (float) The average price of the current position
strategy_openprofit (float) : (float) The current open profit
strategy_opentrades (int) : (int) The number of open trades
isBullishRate (bool) : (bool) If the current rate is bullish
isBearishRate (bool) : (bool) If the current rate is bearish
mlRSIOverSold (bool) : (bool) If the ML RSI is oversold
mlRSIOverBought (bool) : (bool) If the ML RSI is overbought
updateTableNoPosition(tbl)
Updates the table when there is no position
Parameters:
tbl (table) : (table) The table to update
TradingUtilsLibrary "TradingUtils"
Utility library for common trading functions
calcVariation(price, threshold)
Calculates variation of a price based on a threshold
Parameters:
price (float) : (float) The price to be varied
threshold (float) : (float) The threshold for the variation
Returns: (float) The varied price
sendAlert(action, symbol, orderType, quantity, message)
Sends an alert message in JSON format
Parameters:
action (string) : (string) The action to be taken (e.g., "BUY", "SELL")
symbol (string) : (string) The trading symbol (e.g., "BTCUSDT")
orderType (string) : (string) The order type (e.g., "MARKET")
quantity (float) : (float) The quantity of the order
message (string) : (string) The message to be included in the alert
updateLine(condition, index, price, lineColor)
Updates or creates a line on the chart
Parameters:
condition (bool) : (bool) Condition to check if the line should be updated or created
index (int) : (int) The current bar index
price (float) : (float) The price value for the line
lineColor (color) : (color) The color of the line
Returns: (line) The updated or newly created line
JohtiLiquidityThis libraray will be provide the liquity points that's will be help to find exact point people going to take trades and it will the most important area
SessionBoxLibrary "SessionBox"
This library provides functions to manage and visualize session boxes and labels on chart. A session box is a visual representation of a trading session with properties like time, name, color and the ability to track the high and low price within that session.
SessionBox
SessionBox: stores session data and provides methods to manage that data and visualize it on the chart.
Fields:
session_time (series bool)
session_name (series string)
session_color (series color)
time_libraryLibrary "time_library"
This library provides utilities for working with time intervals in milliseconds, seconds, minutes, hours, days, and weeks. It includes functions to handle conditions based on time rather than bars.
ms(TIME)
ms - Converts a time period in string format to milliseconds.
Parameters:
TIME (string) : (series ) - The time period ("ms", "s", "m", "h", "d", "w").
Returns: (int) - The corresponding time period in milliseconds.
true_in(timestamp, period, multiplier)
true_in - Checks if the current time has reached a specific time after the given timestamp.
Parameters:
timestamp (int) : (series ) - The starting timestamp.
period (string) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if current time is equal or past the end date calculated from timestamp and period.
true_in(timestamp, period, multiplier)
true_in - Checks if the current time has reached a specific time after the given timestamp.
Parameters:
timestamp (int) : (series ) - The starting timestamp.
period (int) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if current time is equal or past the end date calculated from timestamp and period.
true_after(trigger, period, multiplier)
true_after - Returns true after a specified period multiplied by a multiplier has passed since a trigger was last true.
Parameters:
trigger (bool) : (series ) - The condition that triggers the timer.
period (string) : (series |series ) - The period in string format ("ms", "s", "m", "h", "d", "w"), or as an integer in milliseconds.
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if the specified time has passed since the last trigger.
true_after(trigger, ms, multiplier)
true_after - Returns true after a specified period multiplied by a multiplier has passed since a trigger was last true.
Parameters:
trigger (bool) : (series ) - The condition that triggers the timer.
ms (int)
multiplier (float) : (series ) - Multiplier to extend the period.
Returns: (bool) - True if the specified time has passed since the last trigger.
MS
MS - Holds common time intervals in milliseconds.
Fields:
ms (series int) : (int) - Milliseconds.
s (series int) : (int) - Seconds converted to milliseconds.
m (series int) : (int) - Minutes converted to milliseconds.
h (series int) : (int) - Hours converted to milliseconds.
d (series int) : (int) - Days converted to milliseconds.
w (series int) : (int) - Weeks converted to milliseconds.
MathTransformLibrary "MathTransform"
Auxiliary functions for transforming data using mathematical and statistical methods
scaler_zscore(x, lookback_window)
Calculates Z-Score normalization of a series.
Parameters:
x (float) : : floating point series to normalize
lookback_window (int) : : lookback period for calculating mean and standard deviation
Returns: Z-Score normalized series
scaler_min_max(x, lookback_window, min_val, max_val, empiric_min, empiric_max, empiric_mid)
Performs Min-Max scaling of a series within a given window, user-defined bounds, and optional midpoint
Parameters:
x (float) : : floating point series to transform
lookback_window (int) : : int : optional lookback window size to consider for scaling.
min_val (float) : : float : minimum value of the scaled range. Default is 0.0.
max_val (float) : : float : maximum value of the scaled range. Default is 1.0.
empiric_min (float) : : float : user-defined minimum value of the input data. This means that the output could exceed the `min_val` bound if there is data in `x` lesser than `empiric_min`. If na, it's calculated from `x` and `lookback_window`.
empiric_max (float) : : float : user-defined maximum value of the input data. This means that the output could exceed the `max_val` bound if there is data in `x` greater than `empiric_max`. If na, it's calculated from `x` and `lookback_window`.
empiric_mid (float) : : float : user-defined midpoint value of the input data. If na, it's calculated from `empiric_min` and `empiric_max`.
Returns: rescaled series
log(x, base)
Applies logarithmic transformation to a value, base can be user-defined.
Parameters:
x (float) : : floating point value to transform
base (float) : : logarithmic base, must be greater than 0
Returns: logarithm of the value to the given base, if x <= 0, returns logarithm of 1 to the given base
exp(x, base)
Applies exponential transformation to a value, base can be user-defined.
Parameters:
x (float) : : floating point value to transform
base (float) : : base of the exponentiation, must be greater than 0
Returns: the result of raising the base to the power of the value
power(x, exponent)
Applies power transformation to a value, exponent can be user-defined.
Parameters:
x (float) : : floating point value to transform
exponent (float) : : exponent for the transformation
Returns: the value raised to the given exponent, preserving the sign of the original value
tanh(x, scale)
The hyperbolic tangent is the ratio of the hyperbolic sine and hyperbolic cosine. It limits an output to a range of −1 to 1.
Parameters:
x (float) : : floating point series
scale (float)
sigmoid(x, scale, offset)
Applies the sigmoid function to a series.
Parameters:
x (float) : : floating point series to transform
scale (float) : : scaling factor for the sigmoid function
offset (float) : : offset for the sigmoid function
Returns: transformed series using the sigmoid function
sigmoid_double(x, scale, offset)
Applies a double sigmoid function to a series, handling positive and negative values differently.
Parameters:
x (float) : : floating point series to transform
scale (float) : : scaling factor for the sigmoid function
offset (float) : : offset for the sigmoid function
Returns: transformed series using the double sigmoid function
logistic_decay(a, b, c, t)
Calculates logistic decay based on given parameters.
Parameters:
a (float) : : parameter affecting the steepness of the curve
b (float) : : parameter affecting the direction of the decay
c (float) : : the upper bound of the function's output
t (float) : : time variable
Returns: value of the logistic decay function at time t
MyLibraryLibrary "MyLibrary"
This library contains various trading strategies and utility functions for Pine Script.
simple_moving_average(src, length)
simple_moving_average
@description Calculates the Simple Moving Average (SMA) of a given series.
Parameters:
src (float) : (series float) The input series (e.g., close prices).
length (int) : (int) The number of periods to use for the SMA calculation.
Returns: (series float) The calculated SMA series.
exponential_moving_average(src, length)
exponential_moving_average
@description Calculates the Exponential Moving Average (EMA) of a given series.
Parameters:
src (float) : (series float) The input series (e.g., close prices).
length (simple int) : (int) The number of periods to use for the EMA calculation.
Returns: (series float) The calculated EMA series.
safe_division(numerator, denominator)
safe_division
@description Performs division with error handling for division by zero.
Parameters:
numerator (float) : (float) The numerator for the division.
denominator (float) : (float) The denominator for the division.
Returns: (float) The result of the division, or na if the denominator is zero.
strategy_moving_average_crossover(shortLength, longLength)
strategy_moving_average_crossover
@description Implements a Moving Average Crossover strategy.
Parameters:
shortLength (int) : (int) The length for the short period SMA.
longLength (int) : (int) The length for the long period SMA.
Returns: (series float, series float, series bool, series bool) The short SMA, long SMA, crossover signals, and crossunder signals.
strategy_rsi(rsiLength, overbought, oversold)
strategy_rsi
@description Implements an RSI-based trading strategy.
Parameters:
rsiLength (simple int) : (int) The length for the RSI calculation.
overbought (float) : (float) The overbought threshold.
oversold (float) : (float) The oversold threshold.
Returns: (series float, series bool, series bool) The RSI values, long signals, and short signals.
ichimoku_cloud(convPeriod, basePeriod, spanBPeriod, laggingSpanPeriod)
ichimoku_cloud
@description Computes Ichimoku Cloud components.
Parameters:
convPeriod (int) : (int) The conversion line period.
basePeriod (int) : (int) The base line period.
spanBPeriod (int)
laggingSpanPeriod (int)
Returns: (series float, series float, series float, series float, series float) The conversion line, base line, leading span A, leading span B, and lagging span.
strategy_ichimoku_conversion_baseline()
strategy_ichimoku_conversion_baseline
@description Implements an Ichimoku Conversion Line and Baseline strategy.
Returns: (series float, series float, series bool, series bool) The conversion line, baseline, crossover signals, and crossunder signals.
debug_print(labelText, value, barIndex)
debug_print
@description Prints values to the chart for debugging purposes.
Parameters:
labelText (string) : (string) The label text.
value (float) : (float) The value to display.
barIndex (int) : (int) The bar index where the label should be displayed.
Cinnamon_Bear Indicators MA LibraryLibrary "Cinnamon_BearIndicatorsMALibrary"
This is a personal Library of the NON built-in PineScript Moving Average function used to code indicators
ma_dema(source, length)
Double Exponential Moving Average (DEMA)
Parameters:
source (simple float)
length (simple int)
Returns: A double level of smoothing helps to follow price movements more closely while still reducing noise compared to a single EMA.
ma_dsma(source, length)
Double Smoothed Moving Average (DSMA)
Parameters:
source (simple float)
length (simple int)
Returns: A double level of smoothing helps to follow price movements more closely while still reducing noise compared to a single SMA.
ma_tema(source, length)
Triple Exponential Moving Average (TEMA)
Parameters:
source (simple float)
length (simple int)
Returns: A Triple level of smoothing helps to follow price movements even more closely compared to a DEMA.
ma_vwema(source, length)
Volume-Weighted Exponential Moving Average (VWEMA)
Parameters:
source (simple float)
length (simple int)
Returns: The VWEMA weights based on volume and recent price, giving more weight to periods with higher trading volumes.
ma_hma(source, length)
Hull Moving Average (HMA)
Parameters:
source (simple float)
length (simple int)
Returns: The HMA formula combines the properties of the weighted moving average (WMA) and the exponential moving average (EMA) to achieve a smoother and more responsive curve.
ma_ehma(source, length)
Enhanced Moving Average (EHMA)
Parameters:
source (simple float)
length (simple int)
Returns: The EHMA is calculated similarly to the Hull Moving Average (HMA) but uses a different weighting factor to further improve responsiveness.
ma_trix(source, length)
Triple Exponential Moving Average (TRIX)
Parameters:
source (simple float)
length (simple int)
Returns: The TRIX is an oscillator that shows the percentage change of a triple EMA. It is designed to filter out minor price movements and display only the most significant trends. The TRIX is a momentum indicator that can help identify trends and buy or sell signals.
ma_lsma(source, length)
Linear Weighted Moving Average (LSMA)
Parameters:
source (simple float)
length (simple int)
Returns: A moving average that gives more weight to recent prices. It is calculated using a formula that assigns linear weights to prices, with the highest weight given to the most recent price and the lowest weight given to the furthest price in the series.
ma_wcma(source, length)
Weighted Cumulative Moving Average (WCMA)
Parameters:
source (simple float)
length (simple int)
Returns: A moving average that gives more weight to recent prices. Compared to a LSMA, the WCMA the weights of data increase linearly with time, so the most recent data has a greater weight compared to older data. This means that the contribution of the most recent data to the moving average is more significant.
ma_vidya(source, length)
Variable Index Dynamic Average (VIDYA)
Parameters:
source (simple float)
length (simple int)
Returns: It is an adaptive moving average that adjusts its momentum based on market volatility using the formula of Chande Momentum Oscillator (CMO) .
ma_zlma(source, length)
Zero-Lag Moving Average (ZLMA)
Parameters:
source (simple float)
length (simple int)
Returns: Its aims to minimize the lag typically associated with MA, designed to react more quickly to price changes.
ma_gma(source, length, power)
Generalized Moving Average (GMA)
Parameters:
source (simple float)
length (simple int)
power (simple int)
Returns: It is a moving average that uses a power parameter to adjust the weight of historical data. This allows the GMA to adapt to various styles of MA.
ma_tma(source, length)
Triangular Moving Average (TMA)
Parameters:
source (simple float)
length (simple int)
Returns: MA more sensitive to changes in recent data compared to the SMA, providing a moving average that better adapts to short-term price changes.
RiskMetrics█ OVERVIEW
This library is a tool for Pine programmers that provides functions for calculating risk-adjusted performance metrics on periodic price returns. The calculations used by this library's functions closely mirror those the Broker Emulator uses to calculate strategy performance metrics (e.g., Sharpe and Sortino ratios) without depending on strategy-specific functionality.
█ CONCEPTS
Returns, risk, and volatility
The return on an investment is the relative gain or loss over a period, often expressed as a percentage. Investment returns can originate from several sources, including capital gains, dividends, and interest income. Many investors seek the highest returns possible in the quest for profit. However, prudent investing and trading entails evaluating such returns against the associated risks (i.e., the uncertainty of returns and the potential for financial losses) for a clearer perspective on overall performance and sustainability.
One way investors and analysts assess the risk of an investment is by analyzing its volatility , i.e., the statistical dispersion of historical returns. Investors often use volatility in risk estimation because it provides a quantifiable way to gauge the expected extent of fluctuation in returns. Elevated volatility implies heightened uncertainty in the market, which suggests higher expected risk. Conversely, low volatility implies relatively stable returns with relatively minimal fluctuations, thus suggesting lower expected risk. Several risk-adjusted performance metrics utilize volatility in their calculations for this reason.
Risk-free rate
The risk-free rate represents the rate of return on a hypothetical investment carrying no risk of financial loss. This theoretical rate provides a benchmark for comparing the returns on a risky investment and evaluating whether its excess returns justify the risks. If an investment's returns are at or below the theoretical risk-free rate or the risk premium is below a desired amount, it may suggest that the returns do not compensate for the extra risk, which might be a call to reassess the investment.
Since the risk-free rate is a theoretical concept, investors often utilize proxies for the rate in practice, such as Treasury bills and other government bonds. Conventionally, analysts consider such instruments "risk-free" for a domestic holder, as they are a form of government obligation with a low perceived likelihood of default.
The average yield on short-term Treasury bills, influenced by economic conditions, monetary policies, and inflation expectations, has historically hovered around 2-3% over the long term. This range also aligns with central banks' inflation targets. As such, one may interpret a value within this range as a minimum proxy for the risk-free rate, as it may correspond to the minimum rate required to maintain purchasing power over time.
The built-in Sharpe and Sortino ratios that strategies calculate and display in the Performance Summary tab use a default risk-free rate of 2%, and the metrics in this library's example code use the same default rate. Users can adjust this value to fit their analysis needs.
Risk-adjusted performance
Risk-adjusted performance metrics gauge the effectiveness of an investment by considering its returns relative to the perceived risk. They aim to provide a more well-rounded picture of performance by factoring in the level of risk taken to achieve returns. Investors can utilize such metrics to help determine whether the returns from an investment justify the risks and make informed decisions.
The two most commonly used risk-adjusted performance metrics are the Sharpe ratio and the Sortino ratio.
1. Sharpe ratio
The Sharpe ratio , developed by Nobel laureate William F. Sharpe, measures the performance of an investment compared to a theoretically risk-free asset, adjusted for the investment risk. The ratio uses the following formula:
Sharpe Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑎
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑎 = Standard deviation of the investment's returns (volatility)
A higher Sharpe ratio indicates a more favorable risk-adjusted return, as it signifies that the investment produced higher excess returns per unit of increase in total perceived risk.
2. Sortino ratio
The Sortino ratio is a modified form of the Sharpe ratio that only considers downside volatility , i.e., the volatility of returns below the theoretical risk-free benchmark. Although it shares close similarities with the Sharpe ratio, it can produce very different values, especially when the returns do not have a symmetrical distribution, since it does not penalize upside and downside volatility equally. The ratio uses the following formula:
Sortino Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑑
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑑 = Downside deviation (standard deviation of negative excess returns, or downside volatility)
The Sortino ratio offers an alternative perspective on an investment's return-generating efficiency since it does not consider upside volatility in its calculation. A higher Sortino ratio signifies that the investment produced higher excess returns per unit of increase in perceived downside risk.
█ CALCULATIONS
Return period detection
Calculating risk-adjusted performance metrics requires collecting returns across several periods of a given size. Analysts may use different period sizes based on the context and their preferences. However, two widely used standards are monthly or daily periods, depending on the available data and the investment's duration. The built-in ratios displayed in the Strategy Tester utilize returns from either monthly or daily periods in their calculations based on the following logic:
• Use monthly returns if the history of closed trades spans at least two months.
• Use daily returns if the trades span at least two days but less than two months.
• Do not calculate the ratios if the trade data spans fewer than two days.
This library's `detectPeriod()` function applies related logic to available chart data rather than trade data to determine which period is appropriate:
• It returns true if the chart's data spans at least two months, indicating that it's sufficient to use monthly periods.
• It returns false if the chart's data spans at least two days but not two months, suggesting the use of daily periods.
• It returns na if the length of the chart's data covers less than two days, signifying that the data is insufficient for meaningful ratio calculations.
It's important to note that programmers should only call `detectPeriod()` from a script's global scope or within the outermost scope of a function called from the global scope, as it requires the time value from the first bar to accurately measure the amount of time covered by the chart's data.
Collecting periodic returns
This library's `getPeriodicReturns()` function tracks price return data within monthly or daily periods and stores the periodic values in an array . It uses a `detectPeriod()` call as the condition to determine whether each element in the array represents the return over a monthly or daily period.
The `getPeriodicReturns()` function has two overloads. The first overload requires two arguments and outputs an array of monthly or daily returns for use in the `sharpe()` and `sortino()` methods. To calculate these returns:
1. The `percentChange` argument should be a series that represents percentage gains or losses. The values can be bar-to-bar return percentages on the chart timeframe or percentages requested from a higher timeframe.
2. The function compounds all non-na `percentChange` values within each monthly or daily period to calculate the period's total return percentage. When the `percentChange` represents returns from a higher timeframe, ensure the requested data includes gaps to avoid compounding redundant values.
3. After a period ends, the function queues the compounded return into the array , removing the oldest element from the array when its size exceeds the `maxPeriods` argument.
The resulting array represents the sequence of closed returns over up to `maxPeriods` months or days, depending on the available data.
The second overload of the function includes an additional `benchmark` parameter. Unlike the first overload, this version tracks and collects differences between the `percentChange` and the specified `benchmark` values. The resulting array represents the sequence of excess returns over up to `maxPeriods` months or days. Passing this array to the `sharpe()` and `sortino()` methods calculates generalized Information ratios , which represent the risk-adjustment performance of a sequence of returns compared to a risky benchmark instead of a risk-free rate. For consistency, ensure the non-na times of the `benchmark` values align with the times of the `percentChange` values.
Ratio methods
This library's `sharpe()` and `sortino()` methods respectively calculate the Sharpe and Sortino ratios based on an array of returns compared to a specified annual benchmark. Both methods adjust the annual benchmark based on the number of periods per year to suit the frequency of the returns:
• If the method call does not include a `periodsPerYear` argument, it uses `detectPeriod()` to determine whether the returns represent monthly or daily values based on the chart's history. If monthly, the method divides the `annualBenchmark` value by 12. If daily, it divides the value by 365.
• If the method call does specify a `periodsPerYear` argument, the argument's value supersedes the automatic calculation, facilitating custom benchmark adjustments, such as dividing by 252 when analyzing collected daily stock returns.
When the array passed to these methods represents a sequence of excess returns , such as the result from the second overload of `getPeriodicReturns()`, use an `annualBenchmark` value of 0 to avoid comparing those excess returns to a separate rate.
By default, these methods only calculate the ratios on the last available bar to minimize their resource usage. Users can override this behavior with the `forceCalc` parameter. When the value is true , the method calculates the ratio on each call if sufficient data is available, regardless of the bar index.
Look first. Then leap.
█ FUNCTIONS & METHODS
This library contains the following functions:
detectPeriod()
Determines whether the chart data has sufficient coverage to use monthly or daily returns
for risk metric calculations.
Returns: (bool) `true` if the period spans more than two months, `false` if it otherwise spans more
than two days, and `na` if the data is insufficient.
getPeriodicReturns(percentChange, maxPeriods)
(Overload 1 of 2) Tracks periodic return percentages and queues them into an array for ratio
calculations. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
maxPeriods (simple int) : (simple int) The maximum number of periodic returns to store in the returned array.
Returns: (array) An array containing the overall percentage changes for each period, limited
to the maximum specified by `maxPeriods`.
getPeriodicReturns(percentChange, benchmark, maxPeriods)
(Overload 2 of 2) Tracks periodic excess return percentages and queues the values into an
array. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
benchmark (float) : (series float) The benchmark percentage to compare against `percentChange` values.
The function compounds non-na values from each bar within monthly or
daily periods and subtracts the results from the compounded `percentChange` values to
calculate the excess returns. For consistency, ensure this series has a similar history
length to the `percentChange` with aligned non-na value times.
maxPeriods (simple int) : (simple int) The maximum number of periodic excess returns to store in the returned array.
Returns: (array) An array containing monthly or daily excess returns, limited
to the maximum specified by `maxPeriods`.
method sharpeRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sharpe ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sharpe ratio, which estimates the excess return per unit of total volatility.
method sortinoRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sortino ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sortino ratio, which estimates the excess return per unit of downside
volatility.
TimeFilterLibrary "TimeFilter"
provides utilities for dates and times
inSession(session, timezone, period)
Parameters:
session (simple string)
timezone (simple string)
period (simple string)
Returns: bool inSession Whether the current time is within the defined time session
inDateRange(startDate, endDate)
Parameters:
startDate (int)
endDate (int)
Returns: bool inRange Whether the current time is within the defined date range
isWeekDay(weekDay, timezone)
Parameters:
weekDay (int)
timezone (simple string)
Returns: bool isWeekDay Whether the provided day is the current day of the week
inWeek(useMon, useTue, useWed, useThu, useFri, useSat, useSun, timezone)
Parameters:
useMon (bool)
useTue (bool)
useWed (bool)
useThu (bool)
useFri (bool)
useSat (bool)
useSun (bool)
timezone (simple string)
Returns: bool inWeek Whether the current time is one of the defined days
filter(useRange, useSession, useWeek, inRange, inSession, inWeek)
Parameters:
useRange (bool)
useSession (bool)
useWeek (bool)
inRange (bool)
inSession (bool)
inWeek (bool)
Returns: bool filter Whether the filter matches or not
FunctionTimeFrequencyLibrary "FunctionTimeFrequency"
Functions to encode time in a normalized space (-0.5, 0.5) that corresponds to the position of the
current time in the referrence frequency of time.
The purpose of normalizing the time value in this manner is to provide a consistent and easily comparable
representation of normalized time that can be used for various calculations or comparisons without needing
to consider the specific scale of time. This function can be particularly useful when working with high-precision
timing data, as it allows you to compare and manipulate time values more flexibly than using absolute second
counts alone.
Reference:
github.com
second_of_minute(t)
Second of minute encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
minute_of_hour(t)
Minute of hour encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
hour_of_day(t)
Hour of day encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_week(t)
Day of week encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_month(t)
Day of month encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
day_of_year(t)
Day of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
month_of_year(t)
Month of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
week_of_year(t)
Week of year encoded as value between (-0.5, 0.5).
Parameters:
t (int) : Time value.
Returns: normalized time.
[ALGOA+] AutofiboLibrary "Autofibo"
fibonacci(up, down, calculate, log, color1, color2, plot)
Creates an array with fibbonaci levels and plots lines.
Parameters:
up (float)
down (float)
calculate (bool)
log (bool)
color1 (color)
color2 (color)
plot (bool)
Returns: --> var float tupple.
fibonacciExtension(up, down, direction, log, calculate, color1, plot)
Fibonacci extension.
@description up (float) Up level.
@description down (float) Down level.
@description direction (string) Options "up" or "down".
Parameters:
up (float)
down (float)
direction (string)
log (bool)
calculate (bool)
color1 (color)
plot (bool)
Returns: -> var float, var float
trendFibo(uptrend, downtrend, log_option, color1, color2, plot)
Calculates automatic fibo values based on trends, returning a tupple with most important values.
Parameters:
uptrend (bool)
downtrend (bool)
log_option (bool)
color1 (color)
color2 (color)
plot (bool)
Returns:
signalLib_yashgode9Signal Generation Library = "signalLib_yashgode9"
This library, named "signalLib_yashgode9", is designed to generate buy and sell signals based on the price action of a financial instrument. It utilizes various technical indicators and parameters to determine the market direction and provide actionable signals for traders.
Key Features:-
1.Trend Direction Identification: The library calculates the trend direction by comparing the number of bars since the highest and lowest prices within a specified depth. This allows the library to determine the overall market direction, whether it's bullish or bearish.
2.Dynamic Price Tracking: The library maintains two chart points, zee1 and zee2, which dynamically track the price levels based on the identified market direction. These points serve as reference levels for generating buy and sell signals.
3.Customizable Parameters: The library allows users to adjust several parameters, including the depth of the price analysis, the deviation threshold, and the number of bars to consider for the trend direction. This flexibility enables users to fine-tune the library's behavior to suit their trading strategies.
4.Visual Representation: The library provides a visual representation of the buy and sell signals by drawing a line between the zee1 and zee2 chart points. The line's color changes based on the identified market direction, with red indicating a bearish signal and green indicating a bullish signal.
Usage and Integration:
To use this library, you can call the "signalLib_yashgode9" function and pass in the necessary parameters, such as the lower and higher prices, the depth of the analysis, the deviation threshold, and the number of bars to consider for the trend direction. The function will return the direction of the market (1 for bullish, -1 for bearish), as well as the zee1 and zee2 chart points.You can then use these values to generate buy and sell signals in your trading strategy. For example, you could use the direction value to determine when to enter or exit a trade, and the zee1 and zee2 chart points to set stop-loss or take-profit levels.
Potential Use Cases:
This library can be particularly useful for traders who:
1.Trend-following Strategies: The library's ability to identify the market direction can be beneficial for traders who employ trend-following strategies, as it can help them identify the dominant trend and time their entries and exits accordingly.
2.Swing Trading: The dynamic price tracking provided by the zee1 and zee2 chart points can be useful for swing traders, who aim to capture medium-term price movements.
3.Automated Trading Systems: The library's functionality can be integrated into automated trading systems, allowing for the development of more sophisticated and rule-based trading strategies.
4.Educational Purposes: The library can also be used for educational purposes, as it provides a clear and concise way to demonstrate the application of technical analysis concepts in a trading context.
Important Notice:- This library effectively work on timeframe of 5-minute and 15-minute.
ColourUtilitiesLibrary "ColourUtilities"
Utility functions for colour manipulation
adjust_colour(rgb, desaturation_amount, transparency_amount)
to reduce saturation or increase transparency of an RGB colour
Parameters:
rgb (color)
desaturation_amount (float) : 0 means no desaturation (colours remains as-is), and 1 means full desaturation (colour turns grey). Can also be used inversely with negative numbers
transparency_amount (float) : How much more transparent the default transparency should become. E.g. with a value of 0.5, a transparency of 0 becomes 50 and 40 becomes 70. A value of 1 makes it fully transparent, en -1 fully opaque.
Returns: color with adjusted saturation and transparency
method apply_default_palette(self, palette_name)
Some nice looking colour palettes, consisting of 6 gradient colours, are already defined here and can be quickly applied to the Palette class
Namespace types: Palette
Parameters:
self (Palette)
palette_name (string) : Currently there are 4 6-coloured palettes available: "GYTS flux signal", "GYTS purple", "GYTS flux filter" and "GYTS maroon"
Returns: None, as it populates the Palette class with pre-defined colours
method get_colour(self, colour_no, transparency)
Retrieves colour from the palette and possibly changes transparency if set
Namespace types: Palette
Parameters:
self (Palette)
colour_no (int) : from the palette
transparency (int) : to possibly change the default transparency of the palette
Returns: colour
method get_dynamic_colour(self, x, mid_point, colour_lb, colour_ub, trend_lookback, use_rate)
Retrieves a colour based on strength and direction of the passed series
Namespace types: Palette
Parameters:
self (Palette)
x (float) : the input data series
mid_point (float) : value as a cutoff point where the bullish/bearish colour scenario
colour_lb (float) : value (lower bound) where to apply the bearish colour at full strength
colour_ub (float) : value (upper bound) where to apply the bullish colour at full strength
trend_lookback (int) : how much bars back to check if there was a consistent move into a certain direction, otherwise a the neutral colour from the centre of the palette will be used.
use_rate (bool) : whether to use the rate (proportional difference with previous `x` value) or the input series `x` directly
Returns: colour
Palette
Fields:
transparency (series__integer)
palette (array__color)
VolumeSpreadAnalysisLibrary "VolumeSpreadAnalysis"
A library for Volume Spread Analysis (VSA).
spread(_barIndex)
Calculates the spread of a bar.
Parameters:
_barIndex (int) : (int) The index of the bar.
Returns: (float) The spread of the bar.
volume(_barIndex)
Retrieves the volume of a bar.
Parameters:
_barIndex (int) : (int) The index of the bar.
Returns: (float) The volume of the bar.
body(_barIndex)
Calculates the body of a bar.
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (float) The body size of the bar.
wickUpper(_barIndex)
Calculates the upper wick of a bar (upper shadow).
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (float) The upper wick size of the bar.
wickLower(_barIndex)
Calculates the lower wick of a bar (lower shadow).
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (float) The lower wick size of the bar.
calcForecastedSMA(_source, _length, _forecastedLevel)
Calculates the forecasted Simple Moving Average (SMA).
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the SMA.
_forecastedLevel (float) : (float) The forecasted level to include in the calculation.
Returns: (float) The forecasted SMA value.
calcForecastedEMA(_source, _length, _forecastedLevel)
Calculates the forecasted Exponential Moving Average (EMA).
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the EMA.
_forecastedLevel (float) : (float) The forecasted level to include in the calculation.
Returns: (float) The forecasted EMA value.
calcForecastedRMA(_source, _length, _forecastedLevel)
Calculates the forecasted Relative Moving Average (RMA).
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the RMA.
_forecastedLevel (float) : (float) The forecasted level to include in the calculation.
Returns: (float) The forecasted RMA value.
calcForecastedWMA(_source, _length, _forecastedLevel)
Calculates the forecasted Weighted Moving Average (WMA).
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the WMA.
_forecastedLevel (float) : (float) The forecasted level to include in the calculation.
Returns: (float) The forecasted WMA value.
calcElapsedTimePercent()
Calculates the elapsed time percent of the current bar.
Returns: (float) The elapsed time percent.
calcForecastedSpread(multiplierAtMidpoints, multiplierAtPeaks)
Calculates the forecasted spread using elapsed time and dynamic multipliers, handling spread's non-linear nature.
Parameters:
multiplierAtMidpoints (float) : (float) The multiplier value at midpoints.
multiplierAtPeaks (float) : (float) The multiplier value at peaks.
Returns: (float) The forecasted spread value.
calcForecastedVolume()
Calculates the forecasted volume using elapsed time, satisfying volume's linear nature.
Returns: (float) The forecasted volume value.
calcForecastedMA(_source, _length, _forecastedSource, _type)
Calculates the forecasted Moving Average (MA) based on the specified type.
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the MA.
_forecastedSource (float) : (float) The forecasted level to include in the calculation.
_type (simple string) : (string) The type of the MA ("SMA", "EMA", "SMMA (RMA)", "WMA").
Returns: (float) The forecasted MA value.
calcMA(_source, _length, _type)
Calculates the Moving Average (MA) based on the specified type.
Parameters:
_source (float) : (series float) Source data for calculation.
_length (simple int) : (int) The length of the MA.
_type (simple string) : (string) The type of the MA ("SMA", "EMA", "SMMA (RMA)", "WMA").
Returns: (float) The MA value.
bullBar(_barIndex)
Determines if the bar is bullish.
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (bool) True if the bar is bullish, otherwise false.
bearBar(_barIndex)
Determines if the bar is bearish.
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (bool) True if the bar is bearish, otherwise false.
breakout(_barIndex)
Determines if there is a breakout above the previous bar.
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (bool) True if there is a breakout, otherwise false.
breakdown(_barIndex)
Determines if there is a breakdown below the previous bar.
Parameters:
_barIndex (simple int) : (int) The index of the bar.
Returns: (bool) True if there is a breakdown, otherwise false.
rejectionWickUpper(_rejectionWick)
Determines if the upper wick is a rejection wick.
Parameters:
_rejectionWick (simple float) : (float) The rejection wick percentage.
Returns: (bool) True if the upper wick is a rejection wick, otherwise false.
rejectionWickLower(_rejectionWick)
Determines if the lower wick is a rejection wick.
Parameters:
_rejectionWick (simple float) : (float) The rejection wick percentage.
Returns: (bool) True if the lower wick is a rejection wick, otherwise false.
setupDataVolume(_data, _mult_Low, _mult_High, _mult_Ultra, _maLengthVolume, _maTypeVolume)
Sets up data for volume levels.
Parameters:
_data (map) : (map) The map to store the levels.
_mult_Low (simple float) : (float) The multiplier for low level.
_mult_High (simple float) : (float) The multiplier for high level.
_mult_Ultra (simple float) : (float) The multiplier for ultra level.
_maLengthVolume (simple int) : (int) The length for MA.
_maTypeVolume (simple string) : (string) The type for MA.
Returns: (void) Nothing.
setupDataSpread(_data, _mult_Low, _mult_High, _mult_Ultra, _maLengthSpread, _maTypeSpread)
Sets up data for spread levels.
Parameters:
_data (map) : (map) The map to store the levels.
_mult_Low (simple float) : (float) The multiplier for low level.
_mult_High (simple float) : (float) The multiplier for high level.
_mult_Ultra (simple float) : (float) The multiplier for ultra level.
_maLengthSpread (simple int) : (int) The length for MA.
_maTypeSpread (simple string) : (string) The type for MA.
Returns: (void) Nothing.
setupDataForecastVolume(_dataForecast, _mult_Low, _mult_High, _mult_Ultra, _maLengthVolume, _predictedLevelVolume, _maTypeVolume)
Sets up data for volume and spread levels for forecast.
Parameters:
_dataForecast (map)
_mult_Low (simple float) : (float) The multiplier for low level.
_mult_High (simple float) : (float) The multiplier for high level.
_mult_Ultra (simple float) : (float) The multiplier for ultra level.
_maLengthVolume (simple int) : (int) The length for MA.
_predictedLevelVolume (float) : (float) The predicted level for MA.
_maTypeVolume (simple string) : (string) The type for MA.
Returns: (void) Nothing.
setupDataForecastSpread(_dataForecast, _mult_Low, _mult_High, _mult_Ultra, _maLengthSpread, _predictedLevelSpread, _maTypeSpread)
Sets up data for spread levels for forecast.
Parameters:
_dataForecast (map)
_mult_Low (simple float) : (float) The multiplier for low level.
_mult_High (simple float) : (float) The multiplier for high level.
_mult_Ultra (simple float) : (float) The multiplier for ultra level.
_maLengthSpread (simple int) : (int) The length for MA.
_predictedLevelSpread (float) : (float) The predicted level for MA.
_maTypeSpread (simple string) : (string) The type for MA.
Returns: (void) Nothing.
isVolumeLow(_data, _barIndex)
Determines if the volume is low.
Parameters:
_data (map) : (map) The data map with volume levels.
_barIndex (int)
Returns: (bool) True if the volume is low, otherwise false.
isVolumeNormal(_data, _barIndex)
Determines if the volume is normal.
Parameters:
_data (map) : (map) The data map with volume levels.
_barIndex (int)
Returns: (bool) True if the volume is normal, otherwise false.
isVolumeHigh(_data, _barIndex)
Determines if the volume is high.
Parameters:
_data (map) : (map) The data map with volume levels.
_barIndex (int)
Returns: (bool) True if the volume is high, otherwise false.
isVolumeUltra(_data, _barIndex)
Determines if the volume is ultra.
Parameters:
_data (map) : (map) The data map with volume levels.
_barIndex (int)
Returns: (bool) True if the volume is ultra, otherwise false.
isSpreadLow(_data, _barIndex)
Determines if the spread is low.
Parameters:
_data (map) : (map) The data map with spread levels.
_barIndex (int)
Returns: (bool) True if the spread is low, otherwise false.
isSpreadNormal(_data, _barIndex)
Determines if the spread is normal.
Parameters:
_data (map) : (map) The data map with spread levels.
_barIndex (int)
Returns: (bool) True if the spread is normal, otherwise false.
isSpreadHigh(_data, _barIndex)
Determines if the spread is high.
Parameters:
_data (map) : (map) The data map with spread levels.
_barIndex (int)
Returns: (bool) True if the spread is high, otherwise false.
isSpreadUltra(_data, _barIndex)
Determines if the spread is ultra.
Parameters:
_data (map) : (map) The data map with spread levels.
_barIndex (int)
Returns: (bool) True if the spread is ultra, otherwise false.
isVolumeText(_data)
Determines text string representing the volume area level.
Parameters:
_data (map) : (map) The data map with volume levels.
Returns: (string) Text string of Low, Normal, High, or Ultra.
isSpreadText(_data)
Determines text string representing the spread area level.
Parameters:
_data (map) : (map) The data map with spread levels.
Returns: (string) Text string of Low, Normal, High, or Ultra.
calcBarColor(_value, _level)
Calculates the color based level.
Parameters:
_value (float) : (float) The value to check.
_level (float) : (float) The value level for comparison.
Returns: (color) The color for the bar.
bullPinBar(_maxBodyPercent, _minWickPercent)
Determines if the bar is a bull pin bar.
Parameters:
_maxBodyPercent (simple float) : (float) The maximum body percentage.
_minWickPercent (simple float) : (float) The minimum wick percentage.
Returns: (bool) True if the bar is a bull pin bar, otherwise false.
bearPinBar(_maxBodyPercent, _minWickPercent)
Determines if the bar is a bear pin bar.
Parameters:
_maxBodyPercent (simple float) : (float) The maximum body percentage.
_minWickPercent (simple float) : (float) The minimum wick percentage.
Returns: (bool) True if the bar is a bear pin bar, otherwise false.
dojiBar(_maxBodyPercent)
Determines if the bar is a doji.
Parameters:
_maxBodyPercent (simple float) : (float) The maximum body percentage.
Returns: (bool) True if the bar is a doji, otherwise false.
spinningTopBar(_minWicksPercent, _emaLength)
Determines if the bar is a spinning top.
Parameters:
_minWicksPercent (simple float) : (float) The minimum wicks percentage.
_emaLength (simple int) : (int) The length for EMA calculation.
Returns: (bool) True if the bar is a spinning top, otherwise false.
highWaveBar(_minBodyPercent, _minWickPercent, _bars)
Determines if the bar is a high wave bar.
Parameters:
_minBodyPercent (simple float) : (float) The minimum body percentage.
_minWickPercent (simple float) : (float) The minimum wick percentage.
_bars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if the bar is a high wave bar, otherwise false.
consolidationBar(_data, _spread, _bars)
Determines if the bars are in consolidation.
Parameters:
_data (map) : (map) The data map with spread levels.
_spread (simple float) : (float) The spread percentage for comparison.
_bars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if the bars are in consolidation, otherwise false.
S_DownThrust(_data, _bullPinBarMaxBody, _bullPinBarMinWick)
Determines if there is a sign of strength (DownThrust).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_bullPinBarMaxBody (simple float) : (float) The maximum body percentage for bull pin bar.
_bullPinBarMinWick (simple float) : (float) The minimum wick percentage for bull pin bar.
Returns: (bool) True if there is a sign of strength (DownThrust), otherwise false.
S_SellingClimax(_data, _rejectionWick)
Determines if there is a sign of strength (Selling Climax).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_rejectionWick (simple float) : (float) The rejection wick percentage.
Returns: (bool) True if there is a sign of strength (Selling Climax), otherwise false.
S_NoEffortBearishResult()
Determines if there is a sign of strength (No Effort Bearish Result).
Returns: (bool) True if there is a sign of strength (No Effort Bearish Result), otherwise false.
S_BearishEffortNoResult()
Determines if there is a sign of strength (Bearish Effort No Result).
Returns: (bool) True if there is a sign of strength (Bearish Effort No Result), otherwise false.
S_InverseDownThrust(_data, _bearPinBarMaxBody, _bearPinBarMinWick)
Determines if there is a sign of strength (Inverse DownThrust).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_bearPinBarMaxBody (simple float) : (float) The maximum body percentage for bear pin bar.
_bearPinBarMinWick (simple float) : (float) The minimum wick percentage for bear pin bar.
Returns: (bool) True if there is a sign of strength (Inverse DownThrust), otherwise false.
S_FailedSellingClimax()
Determines if there is a sign of strength (Failed Selling Climax).
Returns: (bool) True if there is a sign of strength (Failed Selling Climax), otherwise false.
S_BullOutsideReversal(_data)
Determines if there is a sign of strength (Bull Outside Reversal).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
Returns: (bool) True if there is a sign of strength (Bull Outside Reversal), otherwise false.
S_EndOfFallingMarket(_data)
Determines if there is a sign of strength (End of Falling Market).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
Returns: (bool) True if there is a sign of strength (End of Falling Market), otherwise false.
S_PseudoDownThrust(_bullPinBarMaxBody, _bullPinBarMinWick)
Determines if there is a sign of strength (Pseudo DownThrust).
Parameters:
_bullPinBarMaxBody (simple float) : (float) The maximum body percentage for bull pin bar.
_bullPinBarMinWick (simple float) : (float) The minimum wick percentage for bull pin bar.
Returns: (bool) True if there is a sign of strength (Pseudo DownThrust), otherwise false.
S_NoSupply(_bullPinBarMaxBody, _bullPinBarMinWick)
Determines if there is a sign of strength (No Supply).
Parameters:
_bullPinBarMaxBody (simple float) : (float) The maximum body percentage for bull pin bar.
_bullPinBarMinWick (simple float) : (float) The minimum wick percentage for bull pin bar.
Returns: (bool) True if there is a sign of strength (No Supply), otherwise false.
W_UpThrust(_data, _bearPinBarMaxBody, _bearPinBarMinWick)
Determines if there is a sign of weakness (UpThrust).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_bearPinBarMaxBody (simple float) : (float) The maximum body percentage for bear pin bar.
_bearPinBarMinWick (simple float) : (float) The minimum wick percentage for bear pin bar.
Returns: (bool) True if there is a sign of weakness (UpThrust), otherwise false.
W_BuyingClimax(_data, _rejectionWick)
Determines if there is a sign of weakness (Buying Climax).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_rejectionWick (simple float) : (float) The rejection wick percentage.
Returns: (bool) True if there is a sign of weakness (Buying Climax), otherwise false.
W_NoEffortBullishResult()
Determines if there is a sign of weakness (No Effort Bullish Result).
Returns: (bool) True if there is a sign of weakness (No Effort Bullish Result), otherwise false.
W_BullishEffortNoResult()
Determines if there is a sign of weakness (Bullish Effort No Result).
Returns: (bool) True if there is a sign of weakness (Bullish Effort No Result), otherwise false.
W_InverseUpThrust(_data, _bullPinBarMaxBody, _bullPinBarMinWick)
Determines if there is a sign of weakness (Inverse UpThrust).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_bullPinBarMaxBody (simple float) : (float) The maximum body percentage for bull pin bar.
_bullPinBarMinWick (simple float) : (float) The minimum wick percentage for bull pin bar.
Returns: (bool) True if there is a sign of weakness (Inverse UpThrust), otherwise false.
W_FailedBuyingClimax()
Determines if there is a sign of weakness (Failed Buying Climax).
Returns: (bool) True if there is a sign of weakness (Failed Buying Climax), otherwise false.
W_BearOutsideReversal(_data)
Determines if there is a sign of weakness (Bear Outside Reversal).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
Returns: (bool) True if there is a sign of weakness (Bear Outside Reversal), otherwise false.
W_EndOfRisingMarket(_data)
Determines if there is a sign of weakness (End of Rising Market).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
Returns: (bool) True if there is a sign of weakness (End of Rising Market), otherwise false.
W_PseudoUpThrust(_bearPinBarMaxBody, _bearPinBarMinWick)
Determines if there is a sign of weakness (Pseudo UpThrust).
Parameters:
_bearPinBarMaxBody (simple float) : (float) The maximum body percentage for bear pin bar.
_bearPinBarMinWick (simple float) : (float) The minimum wick percentage for bear pin bar.
Returns: (bool) True if there is a sign of weakness (Pseudo UpThrust), otherwise false.
W_NoDemand(_bearPinBarMaxBody, _bearPinBarMinWick)
Determines if there is a sign of weakness (No Demand).
Parameters:
_bearPinBarMaxBody (simple float) : (float) The maximum body percentage for bear pin bar.
_bearPinBarMinWick (simple float) : (float) The minimum wick percentage for bear pin bar.
Returns: (bool) True if there is a sign of weakness (No Demand), otherwise false.
N_QuietDoji(_dojiBarMaxBody)
Determines if there is a neutral signal (Quiet Doji).
Parameters:
_dojiBarMaxBody (simple float) : (float) The maximum body percentage for doji bar.
Returns: (bool) True if there is a neutral signal (Quiet Doji), otherwise false.
N_BalancedDoji(_data, _dojiBarMaxBody)
Determines if there is a neutral signal (Balanced Doji).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_dojiBarMaxBody (simple float) : (float) The maximum body percentage for doji bar.
Returns: (bool) True if there is a neutral signal (Balanced Doji), otherwise false.
N_StrongDoji(_dojiBarMaxBody)
Determines if there is a neutral signal (Strong Doji).
Parameters:
_dojiBarMaxBody (simple float) : (float) The maximum body percentage for doji bar.
Returns: (bool) True if there is a neutral signal (Strong Doji), otherwise false.
N_QuietSpinningTop(_spinningTopBarMinWicks, _spinningTopBarEmaLength)
Determines if there is a neutral signal (Quiet Spinning Top).
Parameters:
_spinningTopBarMinWicks (simple float) : (float) The minimum wicks percentage for spinning top bar.
_spinningTopBarEmaLength (simple int) : (int) The length for EMA calculation.
Returns: (bool) True if there is a neutral signal (Quiet Spinning Top), otherwise false.
N_BalancedSpinningTop(_data, _spinningTopBarMinWicks, _spinningTopBarEmaLength)
Determines if there is a neutral signal (Balanced Spinning Top).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_spinningTopBarMinWicks (simple float) : (float) The minimum wicks percentage for spinning top bar.
_spinningTopBarEmaLength (simple int) : (int) The length for EMA calculation.
Returns: (bool) True if there is a neutral signal (Balanced Spinning Top), otherwise false.
N_StrongSpinningTop(_spinningTopBarMinWicks, _spinningTopBarEmaLength)
Determines if there is a neutral signal (Strong Spinning Top).
Parameters:
_spinningTopBarMinWicks (simple float) : (float) The minimum wicks percentage for spinning top bar.
_spinningTopBarEmaLength (simple int) : (int) The length for EMA calculation.
Returns: (bool) True if there is a neutral signal (Strong Spinning Top), otherwise false.
N_QuietHighWave(_highWaveBarMinBody, _highWaveBarMinWick, _highWaveBarBars)
Determines if there is a neutral signal (Quiet High Wave).
Parameters:
_highWaveBarMinBody (simple float) : (float) The minimum body percentage for high wave bar.
_highWaveBarMinWick (simple float) : (float) The minimum wick percentage for high wave bar.
_highWaveBarBars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if there is a neutral signal (Quiet High Wave), otherwise false.
N_BalancedHighWave(_data, _highWaveBarMinBody, _highWaveBarMinWick, _highWaveBarBars)
Determines if there is a neutral signal (Balanced High Wave).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_highWaveBarMinBody (simple float) : (float) The minimum body percentage for high wave bar.
_highWaveBarMinWick (simple float) : (float) The minimum wick percentage for high wave bar.
_highWaveBarBars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if there is a neutral signal (Balanced High Wave), otherwise false.
N_StrongHighWave(_highWaveBarMinBody, _highWaveBarMinWick, _highWaveBarBars)
Determines if there is a neutral signal (Strong High Wave).
Parameters:
_highWaveBarMinBody (simple float) : (float) The minimum body percentage for high wave bar.
_highWaveBarMinWick (simple float) : (float) The minimum wick percentage for high wave bar.
_highWaveBarBars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if there is a neutral signal (Strong High Wave), otherwise false.
N_Consolidation(_data, _consolidationBarSpread, _consolidationBarBars)
Determines if there is a neutral signal (Consolidation).
Parameters:
_data (map) : (map) The data map with volume and spread levels.
_consolidationBarSpread (simple float) : (float) The spread percentage for consolidation bar.
_consolidationBarBars (simple int) : (int) The number of bars for comparison.
Returns: (bool) True if there is a neutral signal (Consolidation), otherwise false.
Volatility_ZigZag_LibraryThis is a Pine Script library for the public indicator "Volatility ZigZag" by brettkind. For further description, please refer to the information available on the original indicator page.
Library "Volatility_ZigZag_Library"
getValues_andStyling_VolatilityZigZag_byBrettkind(hl_src, SOURCE, length, min_dev_input, stdev_fctr, ZigZag, zz_color, zz_width, zz_devline, zz_points, zz_alert_sign, ZZ_Label, ZZ_Label_clr, rev_text, zz_bars_text, pcabs_text, avg_pcabs_text, pcrel_text, avg_pcrel_text, vol_text, avg_vol_text, input_currency)
Parameters:
hl_src (bool)
SOURCE (float)
length (int)
min_dev_input (float)
stdev_fctr (float)
ZigZag (bool)
zz_color (color)
zz_width (int)
zz_devline (bool)
zz_points (bool)
zz_alert_sign (bool)
ZZ_Label (bool)
ZZ_Label_clr (color)
rev_text (bool)
zz_bars_text (bool)
pcabs_text (bool)
avg_pcabs_text (bool)
pcrel_text (bool)
avg_pcrel_text (bool)
vol_text (bool)
avg_vol_text (bool)
input_currency (string)
getStatisticTable_VolatilityZigZag_byBrettkind(x1, Y1_array, draw_tbl)
Parameters:
x1 (int)
Y1_array (array)
draw_tbl (bool)
TRIGLibrary "TRIG"
degreesToRadians(degrees)
Parameters:
degrees (float)
radiansToDegrees(radians)
Parameters:
radians (float)
rt_get_angleAlphaFromLine(x1, y1, x2, y2, inDegrees)
Parameters:
x1 (int)
y1 (float)
x2 (int)
y2 (float)
inDegrees (bool)
rt_get_angleBetaFromLine(x1, y1, x2, y2)
Parameters:
x1 (int)
y1 (float)
x2 (int)
y2 (float)