lib_divergenceLibrary "lib_divergence"
offers a commonly usable function to detect divergences. This will take the default RSI or other symbols / indicators / oscillators as source data.
divergence(osc, pivot_left_bars, pivot_right_bars, div_min_range, div_max_range, ref_low, ref_high, min_divergence_offset_fraction, min_divergence_offset_dev_len, min_divergence_offset_atr_mul)
Detects Divergences between Price and Oscillator action. For bullish divergences, look at trend lines between lows. For bearish divergences, look at trend lines between highs. (strong) oscillator trending, price opposing it | (medium) oscillator trending, price trend flat | (weak) price opposite trending, oscillator trend flat | (hidden) price trending, oscillator opposing it. Pivot detection is only properly done in oscillator data, reference price data is only compared at the oscillator pivot (speed optimization)
Parameters:
osc (float) : (series float) oscillator data (can be anything, even another instrument price)
pivot_left_bars (simple int) : (simple int) optional number of bars left of a confirmed pivot point, confirming it is the highest/lowest in the range before and up to the pivot (default: 5)
pivot_right_bars (simple int) : (simple int) optional number of bars right of a confirmed pivot point, confirming it is the highest/lowest in the range from and after the pivot (default: 5)
div_min_range (simple int) : (simple int) optional minimum distance to the pivot point creating a divergence (default: 5)
div_max_range (simple int) : (simple int) optional maximum amount of bars in a divergence (default: 50)
ref_low (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: low)
ref_high (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: high)
min_divergence_offset_fraction (simple float) : (simple float) optional scaling factor for the offset zone (xDeviation) around the last oscillator H/L detecting following equal H/Ls (default: 0.01)
min_divergence_offset_dev_len (simple int) : (simple int) optional lookback distance for the deviation detection for the offset zone around the last oscillator H/L detecting following equal H/Ls. Used as well for the ATR that does the equal H/L detection for the reference price. (default: 14)
min_divergence_offset_atr_mul (simple float) : (simple float) optional scaling factor for the offset zone (xATR) around the last price H/L detecting following equal H/Ls (default: 1)
@return A tuple of deviation flags.
MATH
QTALibrary "QTA"
This is simple library for basic Quantitative Technical Analysis for retail investors. One example of it being used can be seen here ().
calculateKellyRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns from bets.
Returns: The calculated Kelly Ratio, which indicates the optimal bet size based on winning and losing probabilities.
calculateAdjustedKellyFraction(kellyRatio, riskTolerance, fedStance)
Parameters:
kellyRatio (float) : The calculated Kelly Ratio.
riskTolerance (float) : A float representing the risk tolerance level.
fedStance (string) : A string indicating the Federal Reserve's stance ("dovish", "hawkish", or neutral).
Returns: The adjusted Kelly Fraction, constrained within the bounds of .
calculateStdDev(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the returns, or 0 if insufficient data.
calculateMaxDrawdown(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The maximum drawdown as a percentage.
calculateEV(avgWinReturn, winProb, avgLossReturn)
Parameters:
avgWinReturn (float) : The average return from winning bets.
winProb (float) : The probability of winning a bet.
avgLossReturn (float) : The average return from losing bets.
Returns: The calculated Expected Value of the bet.
calculateTailRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The Tail Ratio, or na if the 5th percentile is zero to avoid division by zero.
calculateSharpeRatio(avgReturn, riskFreeRate, stdDev)
Parameters:
avgReturn (float) : The average return of the investment.
riskFreeRate (float) : The risk-free rate of return.
stdDev (float) : The standard deviation of the investment's returns.
Returns: The calculated Sharpe Ratio, or na if standard deviation is zero.
calculateDownsideDeviation(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the downside returns, or 0 if no downside returns exist.
calculateSortinoRatio(avgReturn, downsideDeviation)
Parameters:
avgReturn (float) : The average return of the investment.
downsideDeviation (float) : The standard deviation of the downside returns.
Returns: The calculated Sortino Ratio, or na if downside deviation is zero.
calculateVaR(returns, confidenceLevel)
Parameters:
returns (array) : An array of floats representing the returns.
confidenceLevel (float) : A float representing the confidence level (e.g., 0.95 for 95% confidence).
Returns: The Value at Risk at the specified confidence level.
calculateCVaR(returns, varValue)
Parameters:
returns (array) : An array of floats representing the returns.
varValue (float) : The Value at Risk threshold.
Returns: The average Conditional Value at Risk, or na if no returns are below the threshold.
calculateExpectedPriceRange(currentPrice, ev, stdDev, confidenceLevel)
Parameters:
currentPrice (float) : The current price of the asset.
ev (float) : The expected value (in percentage terms).
stdDev (float) : The standard deviation (in percentage terms).
confidenceLevel (float) : The confidence level for the price range (e.g., 1.96 for 95% confidence).
Returns: A tuple containing the minimum and maximum expected prices.
calculateRollingStdDev(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling standard deviation of returns.
calculateRollingVariance(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling variance of returns.
calculateRollingMean(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling mean of returns.
calculateRollingCoefficientOfVariation(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling coefficient of variation of returns.
calculateRollingSumOfPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling sum of percent returns.
calculateRollingCumulativeProduct(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling cumulative product of returns.
calculateRollingCorrelation(priceReturns, volumeReturns, window)
Parameters:
priceReturns (array) : An array of floats representing the price returns.
volumeReturns (array) : An array of floats representing the volume returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling correlation.
calculateRollingPercentile(returns, window, percentile)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
percentile (int) : An integer representing the desired percentile (0-100).
Returns: An array of floats representing the rolling percentile of returns.
calculateRollingMaxMinPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: A tuple containing two arrays: rolling max and rolling min percent returns.
calculateRollingPriceToVolumeRatio(price, volData, window)
Parameters:
price (array) : An array of floats representing the price data.
volData (array) : An array of floats representing the volume data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling price-to-volume ratio.
determineMarketRegime(priceChanges)
Parameters:
priceChanges (array) : An array of floats representing the price changes.
Returns: A string indicating the market regime ("Bull", "Bear", or "Neutral").
determineVolatilityRegime(price, window)
Parameters:
price (array) : An array of floats representing the price data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the calculated volatility.
classifyVolatilityRegime(volatility)
Parameters:
volatility (array) : An array of floats representing the calculated volatility.
Returns: A string indicating the volatility regime ("Low" or "High").
method percentPositive(thisArray)
Returns the percentage of positive non-na values in this array.
This method calculates the percentage of positive values in the provided array, ignoring NA values.
Namespace types: array
Parameters:
thisArray (array)
_candleRange()
_PreviousCandleRange(barsback)
Parameters:
barsback (int) : An integer representing how far back you want to get a range
redCandle()
greenCandle()
_WhiteBody()
_BlackBody()
HighOpenDiff()
OpenLowDiff()
_isCloseAbovePreviousOpen(length)
Parameters:
length (int)
_isCloseBelowPrevious()
_isOpenGreaterThanPrevious()
_isOpenLessThanPrevious()
BodyHigh()
BodyLow()
_candleBody()
_BodyAvg(length)
_BodyAvg function.
Parameters:
length (simple int) : Required (recommended is 6).
_SmallBody(length)
Parameters:
length (simple int) : Length of the slow EMA
Returns: a series of bools, after checking if the candle body was less than body average.
_LongBody(length)
Parameters:
length (simple int)
bearWick()
bearWick() function.
Returns: a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
bullWick()
barlength()
sumbarlength()
sumbull()
sumbear()
bull_vol()
bear_vol()
volumeFightMA()
volumeFightDelta()
weightedAVG_BullVolume()
weightedAVG_BearVolume()
VolumeFightDiff()
VolumeFightFlatFilter()
avg_bull_vol(userMA)
avg_bull_vol(int) function.
Parameters:
userMA (int)
avg_bear_vol(userMA)
avg_bear_vol(int) function.
Parameters:
userMA (int)
diff_vol(userMA)
diff_vol(int) function.
Parameters:
userMA (int)
vol_flat(userMA)
vol_flat(int) function.
Parameters:
userMA (int)
_isEngulfingBullish()
_isEngulfingBearish()
dojiup()
dojidown()
EveningStar()
MorningStar()
ShootingStar()
Hammer()
InvertedHammer()
BearishHarami()
BullishHarami()
BullishBelt()
BullishKicker()
BearishKicker()
HangingMan()
DarkCloudCover()
IndicatorsLibrary "Indicators"
cmf(lookback, n_to_smooth)
Calculates the Chaikin's Money Flow.
Parameters:
lookback (simple int)
n_to_smooth (simple int)
Returns: float The Money Flow value.
cmma(lookback, atr_length)
Calculates the CMMA (Close Minus Moving Average) indicator.
Parameters:
lookback (simple int)
atr_length (simple int)
Returns: float The CMMA value.
macd(fast_length, slow_length, n_to_smooth)
Calculates the normalized and scaled MACD.
Parameters:
fast_length (simple int)
slow_length (simple int)
n_to_smooth (simple int)
Returns: A tuple containing .
stochK(length, n_to_smooth)
Calculates a simplified Stochastic Oscillator.
Uses: 100 * ta.sma((close - lowest_low) / (highest_high - lowest_low), n_to_smooth)
Parameters:
length (simple int)
n_to_smooth (simple int)
Returns: float The Stochastic %K value.
williamsR(length)
Calculates the Williams %R using the stochK function.
Uses: -1 * (100 - stoch(length, 1))
Parameters:
length (simple int)
Returns: float The Williams %R value.
lib_kernelLibrary "lib_kernel"
Library "lib_kernel"
This is a tool / library for developers, that contains several common and adapted kernel functions as well as a kernel regression function and enum to easily select and embed a list into the settings dialog.
How to Choose and Modify Kernels in Practice
Compact Support Kernels (e.g., Epanechnikov, Triangular): Use for localized smoothing and emphasizing nearby data.
Oscillatory Kernels (e.g., Wave, Cosine): Ideal for detecting periodic patterns or mean-reverting behavior.
Smooth Tapering Kernels (e.g., Gaussian, Logistic): Use for smoothing long-term trends or identifying global price behavior.
kernel_Epanechnikov(u)
Parameters:
u (float)
kernel_Epanechnikov_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel_Triangular(u)
Parameters:
u (float)
kernel_Triangular_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel_Rectangular(u)
Parameters:
u (float)
kernel_Uniform(u)
Parameters:
u (float)
kernel_Uniform_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel_Logistic(u)
Parameters:
u (float)
kernel_Logistic_alt(u)
Parameters:
u (float)
kernel_Logistic_alt2(u, sigmoid_steepness)
Parameters:
u (float)
sigmoid_steepness (float)
kernel_Gaussian(u)
Parameters:
u (float)
kernel_Gaussian_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel_Silverman(u)
Parameters:
u (float)
kernel_Quartic(u)
Parameters:
u (float)
kernel_Quartic_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel_Biweight(u)
Parameters:
u (float)
kernel_Triweight(u)
Parameters:
u (float)
kernel_Sinc(u)
Parameters:
u (float)
kernel_Wave(u)
Parameters:
u (float)
kernel_Wave_alt(u)
Parameters:
u (float)
kernel_Cosine(u)
Parameters:
u (float)
kernel_Cosine_alt(u, sensitivity)
Parameters:
u (float)
sensitivity (float)
kernel(u, select, alt_modificator)
wrapper for all standard kernel functions, see enum Kernel comments and function descriptions for usage szenarios and parameters
Parameters:
u (float)
select (series Kernel)
alt_modificator (float)
kernel_regression(src, bandwidth, kernel, exponential_distance, alt_modificator)
wrapper for kernel regression with all standard kernel functions, see enum Kernel comments for usage szenarios. performance optimized version using fixed bandwidth and target
Parameters:
src (float) : input data series
bandwidth (simple int) : sample window of nearest neighbours for the kernel to process
kernel (simple Kernel) : type of Kernel to use for processing, see Kernel enum or respective functions for more details
exponential_distance (simple bool) : if true this puts more emphasis on local / more recent values
alt_modificator (float) : see kernel functions for parameter descriptions. Mostly used to pronounce emphasis on local values or introduce a decay/dampening to the kernel output
ManipulationLegHelperLibraryLibrary "ManipulationLegHelperLibrary"
TODO: add library description here
devToArray(dev)
Parameters:
dev (string)
getDev(d, bull, h, l)
Parameters:
d (float)
bull (bool)
h (float)
l (float)
getBearLeg(sweeps, minLegSize, drawLegBox, boxColor)
Parameters:
sweeps (int)
minLegSize (float)
drawLegBox (bool)
boxColor (color)
getBullLeg(sweeps, minSize, drawBox, boxColor)
Parameters:
sweeps (int)
minSize (float)
drawBox (bool)
boxColor (color)
leg
Fields:
time (series int)
low (series float)
high (series float)
edge (series bool)
edge_price (series float)
validated (series int)
sweeps (series int)
barC (series int)
bx (series box)
lib_smcLibrary "lib_smc"
This is an adaptation of LuxAlgo's Smart Money Concepts indicator with numerous changes. Main changes include integration of object based plotting, plenty of performance improvements, live tracking of Order Blocks, integration of volume profiles to refine Order Blocks, and many more.
This is a library for developers, if you want this converted into a working strategy, let me know.
buffer(item, len, force_rotate)
Parameters:
item (float)
len (int)
force_rotate (bool)
buffer(item, len, force_rotate)
Parameters:
item (int)
len (int)
force_rotate (bool)
buffer(item, len, force_rotate)
Parameters:
item (Profile type from robbatt/lib_profile/32)
len (int)
force_rotate (bool)
swings(len)
INTERNAL: detect swing points (HH and LL) in given range
Parameters:
len (simple int) : range to check for new swing points
Returns: values are the price level where and if a new HH or LL was detected, else na
method init(this)
Namespace types: OrderBlockConfig
Parameters:
this (OrderBlockConfig)
method delete(this)
Namespace types: OrderBlock
Parameters:
this (OrderBlock)
method clear_broken(this, broken_buffer)
INTERNAL: delete internal order blocks box coordinates if top/bottom is broken
Namespace types: map
Parameters:
this (map)
broken_buffer (map)
Returns: any_bull_ob_broken, any_bear_ob_broken, broken signals are true if an according order block was broken/mitigated, broken contains the broken block(s)
create_ob(id, mode, start_t, start_i, top, end_t, end_i, bottom, break_price, early_confirmation_price, config, init_plot, force_overlay)
INTERNAL: set internal order block coordinates
Parameters:
id (int)
mode (int) : 1: bullish, -1 bearish block
start_t (int)
start_i (int)
top (float)
end_t (int)
end_i (int)
bottom (float)
break_price (float)
early_confirmation_price (float)
config (OrderBlockConfig)
init_plot (bool)
force_overlay (bool)
Returns: signals are true if an according order block was broken/mitigated
method align_to_profile(block, align_edge, align_break_price)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
align_edge (bool)
align_break_price (bool)
method create_profile(block, opens, tops, bottoms, closes, values, resolution, vah_pc, val_pc, args, init_calculated, init_plot, force_overlay)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
opens (array)
tops (array)
bottoms (array)
closes (array)
values (array)
resolution (int)
vah_pc (float)
val_pc (float)
args (ProfileArgs type from robbatt/lib_profile/32)
init_calculated (bool)
init_plot (bool)
force_overlay (bool)
method create_profile(block, resolution, vah_pc, val_pc, args, init_calculated, init_plot, force_overlay)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
resolution (int)
vah_pc (float)
val_pc (float)
args (ProfileArgs type from robbatt/lib_profile/32)
init_calculated (bool)
init_plot (bool)
force_overlay (bool)
track_obs(swing_len, hh, ll, top, btm, bull_bos_alert, bull_choch_alert, bear_bos_alert, bear_choch_alert, min_block_size, max_block_size, config_bull, config_bear, init_plot, force_overlay, enabled, extend_blocks, clear_broken_buffer_before, align_edge_to_value_area, align_break_price_to_poc, profile_args_bull, profile_args_bear, use_soft_confirm, soft_confirm_offset, use_retracements_with_FVG_out)
Parameters:
swing_len (int)
hh (float)
ll (float)
top (float)
btm (float)
bull_bos_alert (bool)
bull_choch_alert (bool)
bear_bos_alert (bool)
bear_choch_alert (bool)
min_block_size (float)
max_block_size (float)
config_bull (OrderBlockConfig)
config_bear (OrderBlockConfig)
init_plot (bool)
force_overlay (bool)
enabled (bool)
extend_blocks (simple bool)
clear_broken_buffer_before (simple bool)
align_edge_to_value_area (simple bool)
align_break_price_to_poc (simple bool)
profile_args_bull (ProfileArgs type from robbatt/lib_profile/32)
profile_args_bear (ProfileArgs type from robbatt/lib_profile/32)
use_soft_confirm (simple bool)
soft_confirm_offset (float)
use_retracements_with_FVG_out (simple bool)
method draw(this, config, extend_only)
Namespace types: OrderBlock
Parameters:
this (OrderBlock)
config (OrderBlockConfig)
extend_only (bool)
method draw(blocks, config)
INTERNAL: plot order blocks
Namespace types: array
Parameters:
blocks (array)
config (OrderBlockConfig)
method draw(blocks, config)
INTERNAL: plot order blocks
Namespace types: map
Parameters:
blocks (map)
config (OrderBlockConfig)
method cleanup(this, ob_bull, ob_bear)
removes all Profiles that are older than the latest OrderBlock from this profile buffer
Namespace types: array
Parameters:
this (array type from robbatt/lib_profile/32)
ob_bull (OrderBlock)
ob_bear (OrderBlock)
_plot_swing_points(mode, x, y, show_swing_points, linecolor_swings, keep_history, show_latest_swings_levels, trail_x, trail_y, trend)
INTERNAL: plot swing points
Parameters:
mode (int) : 1: bullish, -1 bearish block
x (int) : x-coordingate of swing point to plot (bar_index)
y (float) : y-coordingate of swing point to plot (price)
show_swing_points (bool) : switch to enable/disable plotting of swing point labels
linecolor_swings (color) : color for swing point labels and lates level lines
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
show_latest_swings_levels (bool)
trail_x (int) : x-coordinate for latest swing point (bar_index)
trail_y (float) : y-coordinate for latest swing point (price)
trend (int) : the current trend 1: bullish, -1: bearish, to determine Strong/Weak Low/Highs
_pivot_lvl(mode, trend, hhll_x, hhll, super_hhll, filter_insignificant_internal_breaks)
INTERNAL: detect whether a structural level has been broken and if it was in trend direction (BoS) or against trend direction (ChoCh), also track the latest high and low swing points
Parameters:
mode (simple int) : detect 1: bullish, -1 bearish pivot points
trend (int) : current trend direction
hhll_x (int) : x-coordinate of newly detected hh/ll (bar_index)
hhll (float) : y-coordinate of newly detected hh/ll (price)
super_hhll (float) : level/y-coordinate of superior hhll (if this is an internal structure pivot level)
filter_insignificant_internal_breaks (bool) : if true pivot points / internal structure will be ignored where the wick in trend direction is longer than the opposite (likely to push further in direction of main trend)
Returns: coordinates of internal structure that has been broken (x,y): start of structure, (trail_x, trail_y): tracking hh/ll after structure break, (bos_alert, choch_alert): signal whether a structural level has been broken
_plot_structure(x, y, is_bos, is_choch, line_color, line_style, label_style, label_size, keep_history)
INTERNAL: plot structural breaks (BoS/ChoCh)
Parameters:
x (int) : x-coordinate of newly broken structure (bar_index)
y (float) : y-coordinate of newly broken structure (price)
is_bos (bool) : whether this structural break was in trend direction
is_choch (bool) : whether this structural break was against trend direction
line_color (color) : color for the line connecting the structural level and the breaking candle
line_style (string) : style (line.style_dashed/solid) for the line connecting the structural level and the breaking candle
label_style (string) : style (label.style_label_down/up) for the label above/below the line connecting the structural level and the breaking candle
label_size (string) : size (size.small/tiny) for the label above/below the line connecting the structural level and the breaking candle
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
structure_values(length, super_hh, super_ll, filter_insignificant_internal_breaks)
detect (and plot) structural breaks and the resulting new trend
Parameters:
length (simple int) : lookback period for swing point detection
super_hh (float) : level/y-coordinate of superior hh (for internal structure detection)
super_ll (float) : level/y-coordinate of superior ll (for internal structure detection)
filter_insignificant_internal_breaks (bool) : if true pivot points / internal structure will be ignored where the wick in trend direction is longer than the opposite (likely to push further in direction of main trend)
Returns: trend: direction 1:bullish -1:bearish, (bull_bos_alert, bull_choch_alert, top_x, top_y, trail_up_x, trail_up): whether and which level broke in a bullish direction, trailing high, (bbear_bos_alert, bear_choch_alert, tm_x, btm_y, trail_dn_x, trail_dn): same in bearish direction
structure_plot(trend, bull_bos_alert, bull_choch_alert, top_x, top_y, trail_up_x, trail_up, hh, bear_bos_alert, bear_choch_alert, btm_x, btm_y, trail_dn_x, trail_dn, ll, color_bull, color_bear, show_swing_points, show_latest_swings_levels, show_bos, show_choch, line_style, label_size, keep_history)
detect (and plot) structural breaks and the resulting new trend
Parameters:
trend (int) : crrent trend 1: bullish, -1: bearish
bull_bos_alert (bool) : if there was a bullish bos alert -> plot it
bull_choch_alert (bool) : if there was a bullish choch alert -> plot it
top_x (int) : latest shwing high x
top_y (float) : latest swing high y
trail_up_x (int) : trailing high x
trail_up (float) : trailing high y
hh (float) : if there was a higher high
bear_bos_alert (bool) : if there was a bearish bos alert -> plot it
bear_choch_alert (bool) : if there was a bearish chock alert -> plot it
btm_x (int) : latest swing low x
btm_y (float) : latest swing low y
trail_dn_x (int) : trailing low x
trail_dn (float) : trailing low y
ll (float) : if there was a lower low
color_bull (color) : color for bullish BoS/ChoCh levels
color_bear (color) : color for bearish BoS/ChoCh levels
show_swing_points (bool) : whether to plot swing point labels
show_latest_swings_levels (bool) : whether to track and plot latest swing point levels with lines
show_bos (bool) : whether to plot BoS levels
show_choch (bool) : whether to plot ChoCh levels
line_style (string) : whether to plot BoS levels
label_size (string) : label size of plotted BoS/ChoCh levels
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
structure(length, color_bull, color_bear, super_hh, super_ll, filter_insignificant_internal_breaks, show_swing_points, show_latest_swings_levels, show_bos, show_choch, line_style, label_size, keep_history, enabled)
detect (and plot) structural breaks and the resulting new trend
Parameters:
length (simple int) : lookback period for swing point detection
color_bull (color) : color for bullish BoS/ChoCh levels
color_bear (color) : color for bearish BoS/ChoCh levels
super_hh (float) : level/y-coordinate of superior hh (for internal structure detection)
super_ll (float) : level/y-coordinate of superior ll (for internal structure detection)
filter_insignificant_internal_breaks (bool) : if true pivot points / internal structure will be ignored where the wick in trend direction is longer than the opposite (likely to push further in direction of main trend)
show_swing_points (bool) : whether to plot swing point labels
show_latest_swings_levels (bool) : whether to track and plot latest swing point levels with lines
show_bos (bool) : whether to plot BoS levels
show_choch (bool) : whether to plot ChoCh levels
line_style (string) : whether to plot BoS levels
label_size (string) : label size of plotted BoS/ChoCh levels
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
enabled (bool)
_check_equal_level(mode, len, eq_threshold, enabled)
INTERNAL: detect equal levels (double top/bottom)
Parameters:
mode (int) : detect 1: bullish/high, -1 bearish/low pivot points
len (int) : lookback period for equal level (swing point) detection
eq_threshold (float) : maximum price offset for a level to be considered equal
enabled (bool)
Returns: eq_alert whether an equal level was detected and coordinates of the first and the second level/swing point
_plot_equal_level(show_eq, x1, y1, x2, y2, label_txt, label_style, label_size, line_color, line_style, keep_history)
INTERNAL: plot equal levels (double top/bottom)
Parameters:
show_eq (bool) : whether to plot the level or not
x1 (int) : x-coordinate of the first level / swing point
y1 (float) : y-coordinate of the first level / swing point
x2 (int) : x-coordinate of the second level / swing point
y2 (float) : y-coordinate of the second level / swing point
label_txt (string) : text for the label above/below the line connecting the equal levels
label_style (string) : style (label.style_label_down/up) for the label above/below the line connecting the equal levels
label_size (string) : size (size.tiny) for the label above/below the line connecting the equal levels
line_color (color) : color for the line connecting the equal levels (and it's label)
line_style (string) : style (line.style_dotted) for the line connecting the equal levels
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
equal_levels_values(len, threshold, enabled)
detect (and plot) equal levels (double top/bottom), returns coordinates
Parameters:
len (int) : lookback period for equal level (swing point) detection
threshold (float) : maximum price offset for a level to be considered equal
enabled (bool) : whether detection is enabled
Returns: (eqh_alert, eqh_x1, eqh_y1, eqh_x2, eqh_y2) whether an equal high was detected and coordinates of the first and the second level/swing point, (eql_alert, eql_x1, eql_y1, eql_x2, eql_y2) same for equal lows
equal_levels_plot(eqh_x1, eqh_y1, eqh_x2, eqh_y2, eql_x1, eql_y1, eql_x2, eql_y2, color_eqh, color_eql, show, keep_history)
detect (and plot) equal levels (double top/bottom), returns coordinates
Parameters:
eqh_x1 (int) : coordinates of first point of equal high
eqh_y1 (float) : coordinates of first point of equal high
eqh_x2 (int) : coordinates of second point of equal high
eqh_y2 (float) : coordinates of second point of equal high
eql_x1 (int) : coordinates of first point of equal low
eql_y1 (float) : coordinates of first point of equal low
eql_x2 (int) : coordinates of second point of equal low
eql_y2 (float) : coordinates of second point of equal low
color_eqh (color) : color for the line connecting the equal highs (and it's label)
color_eql (color) : color for the line connecting the equal lows (and it's label)
show (bool) : whether plotting is enabled
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
Returns: (eqh_alert, eqh_x1, eqh_y1, eqh_x2, eqh_y2) whether an equal high was detected and coordinates of the first and the second level/swing point, (eql_alert, eql_x1, eql_y1, eql_x2, eql_y2) same for equal lows
equal_levels(len, threshold, color_eqh, color_eql, enabled, show, keep_history)
detect (and plot) equal levels (double top/bottom)
Parameters:
len (int) : lookback period for equal level (swing point) detection
threshold (float) : maximum price offset for a level to be considered equal
color_eqh (color) : color for the line connecting the equal highs (and it's label)
color_eql (color) : color for the line connecting the equal lows (and it's label)
enabled (bool) : whether detection is enabled
show (bool) : whether plotting is enabled
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
Returns: (eqh_alert) whether an equal high was detected, (eql_alert) same for equal lows
_detect_fvg(mode, enabled, o, h, l, c, filter_insignificant_fvgs, change_tf)
INTERNAL: detect FVG (fair value gap)
Parameters:
mode (int) : detect 1: bullish, -1 bearish gaps
enabled (bool) : whether detection is enabled
o (float) : reference source open
h (float) : reference source high
l (float) : reference source low
c (float) : reference source close
filter_insignificant_fvgs (bool) : whether to calculate and filter small/insignificant gaps
change_tf (bool) : signal when the previous reference timeframe closed, triggers new calculation
Returns: whether a new FVG was detected and its top/mid/bottom levels
_clear_broken_fvg(mode, upper_boxes, lower_boxes)
INTERNAL: clear mitigated FVGs (fair value gaps)
Parameters:
mode (int) : detect 1: bullish, -1 bearish gaps
upper_boxes (array) : array that stores the upper parts of the FVG boxes
lower_boxes (array) : array that stores the lower parts of the FVG boxes
_plot_fvg(mode, show, top, mid, btm, border_color, extend_box)
INTERNAL: plot (and clear broken) FVG (fair value gap)
Parameters:
mode (int) : plot 1: bullish, -1 bearish gap
show (bool) : whether plotting is enabled
top (float) : top level of fvg
mid (float) : center level of fvg
btm (float) : bottom level of fvg
border_color (color) : color for the FVG box
extend_box (int) : how many bars into the future the FVG box should be extended after detection
fvgs_values(o, h, l, c, filter_insignificant_fvgs, change_tf, enabled)
detect (and plot / clear broken) FVGs (fair value gaps), and return alerts and level values
Parameters:
o (float) : reference source open
h (float) : reference source high
l (float) : reference source low
c (float) : reference source close
filter_insignificant_fvgs (bool) : whether to calculate and filter small/insignificant gaps
change_tf (bool) : signal when the previous reference timeframe closed, triggers new calculation
enabled (bool) : whether detection is enabled
Returns: (bullish_fvg_alert, bull_top, bull_mid, bull_btm): whether a new bullish FVG was detected and its top/mid/bottom levels, (bearish_fvg_alert, bear_top, bear_mid, bear_btm): same for bearish FVGs
fvgs_plot(bullish_fvg_alert, bull_top, bull_mid, bull_btm, bearish_fvg_alert, bear_top, bear_mid, bear_btm, color_bull, color_bear, extend_box, show)
Parameters:
bullish_fvg_alert (bool)
bull_top (float)
bull_mid (float)
bull_btm (float)
bearish_fvg_alert (bool)
bear_top (float)
bear_mid (float)
bear_btm (float)
color_bull (color) : color for bullish FVG boxes
color_bear (color) : color for bearish FVG boxes
extend_box (int) : how many bars into the future the FVG box should be extended after detection
show (bool) : whether plotting is enabled
Returns: (bullish_fvg_alert, bull_top, bull_mid, bull_btm): whether a new bullish FVG was detected and its top/mid/bottom levels, (bearish_fvg_alert, bear_top, bear_mid, bear_btm): same for bearish FVGs
fvgs(o, h, l, c, filter_insignificant_fvgs, change_tf, color_bull, color_bear, extend_box, enabled, show)
detect (and plot / clear broken) FVGs (fair value gaps)
Parameters:
o (float) : reference source open
h (float) : reference source high
l (float) : reference source low
c (float) : reference source close
filter_insignificant_fvgs (bool) : whether to calculate and filter small/insignificant gaps
change_tf (bool) : signal when the previous reference timeframe closed, triggers new calculation
color_bull (color) : color for bullish FVG boxes
color_bear (color) : color for bearish FVG boxes
extend_box (int) : how many bars into the future the FVG box should be extended after detection
enabled (bool) : whether detection is enabled
show (bool) : whether plotting is enabled
Returns: (bullish_fvg_alert): whether a new bullish FVG was detected, (bearish_fvg_alert): same for bearish FVGs
OrderBlock
Fields:
id (series int)
dir (series int)
left_top (chart.point)
right_bottom (chart.point)
break_price (series float)
early_confirmation_price (series float)
ltf_high (array)
ltf_low (array)
ltf_volume (array)
plot (Box type from robbatt/lib_plot_objects/49)
profile (Profile type from robbatt/lib_profile/32)
trailing (series bool)
extending (series bool)
awaiting_confirmation (series bool)
touched_break_price_before_confirmation (series bool)
soft_confirmed (series bool)
has_fvg_out (series bool)
hidden (series bool)
broken (series bool)
OrderBlockConfig
Fields:
show (series bool)
show_last (series int)
show_id (series bool)
show_profile (series bool)
args (BoxArgs type from robbatt/lib_plot_objects/49)
txt (series string)
txt_args (BoxTextArgs type from robbatt/lib_plot_objects/49)
delete_when_broken (series bool)
broken_args (BoxArgs type from robbatt/lib_plot_objects/49)
broken_txt (series string)
broken_txt_args (BoxTextArgs type from robbatt/lib_plot_objects/49)
broken_profile_args (ProfileArgs type from robbatt/lib_profile/32)
use_profile (series bool)
profile_args (ProfileArgs type from robbatt/lib_profile/32)
FibRatiosLibrary "FibRatios"
Library with calculation logic for fib retracement, extension and ratios
retracement(a, b, ratio, logScale, precision)
Calculates the retracement for points a, b with given ratio and scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
ratio (float) : Ratio for which we need to calculate retracement c
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: retracement point c for points a,b with given ratio and scale
retracementRatio(a, b, c, logScale, precision)
Calculates the retracement ratio for points a, b, c with given scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: retracement ratio for points a,b,c on given scale
extension(a, b, c, ratio, logScale, precision)
Calculates the extensions for points a, b, c with given ratio and scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
ratio (float) : Ratio for which we need to calculate extension d
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: extensoin point d for points a,b,c with given ratio and scale
extensionRatio(a, b, c, d, logScale, precision)
Calculates the extension ratio for points a, b, c, d with given scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
d (float) : Extension point. d should be placed beyond a, c. But, can be with b,c or beyond b
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: extension ratio for points a,b,c,d on given scale
OutofOptionsHelperLibraryLibrary "OutofOptionsHelperLibrary"
Helper library for my indicators/strategies
isUp(i)
is Up candle
Parameters:
i (int)
Returns: bool
isDown(i)
is Down candle
Parameters:
i (int)
Returns: bool
TF(t)
format time into date/time string
Parameters:
t (int)
Returns: string
S(s)
format data to string
Parameters:
s (float)
Returns: string
S(s)
format data to string
Parameters:
s (int)
Returns: string
S(s)
format data to string
Parameters:
s (bool)
Returns: string
barClose(price, up, strict)
Determine if candle closed above/below price
Parameters:
price (float)
up (bool)
strict (bool) : bool if close over is required or if close at the price is good enough
Returns: bool
processSweep(L, price, up, leftB)
Determine how many liquidity sweeps were made
Parameters:
L (array)
price (float)
up (bool)
leftB (int)
Returns: int
liquidity
Fields:
price (series float)
time (series int)
oprice (series float)
otime (series int)
sweeps (series int)
bars_swept (series int)
MathHelpersLibrary "MathHelpers"
Overview
A collection of helper functions for designing indicators and strategies.
calculateATR(length, log)
Calculates the Average True Range (ATR) or Log ATR based on the 'log' parameter. Sans Wilder's Smoothing
Parameters:
length (simple int)
log (simple bool)
Returns: float The calculated ATR value. Returns Log ATR if `log` is true, otherwise returns standard ATR.
CDF(z)
Computes the Cumulative Distribution Function (CDF) for a given value 'z', mimicking the CDF function in "Statistically Sound Indicators" by Timothy Masters.
Parameters:
z (simple float)
Returns: float The CDF value corresponding to the input `z`, ranging between 0 and 1.
logReturns(lookback)
Calculates the logarithmic returns over a specified lookback period.
Parameters:
lookback (simple int)
Returns: float The calculated logarithmic return. Returns `na` if insufficient data is available.
lib_momentumLibrary "lib_momentum"
This library calculates the momentum, derived from a sample range of prior candles. Depending on set MomentumType it either deduces the momentum from the price, volume, or a product of both. If price/product are selected, you can choose from SampleType if only candle body, full range from high to low or a combination of both (body counts full, wicks half for each direction) should be used. Optional: You can choose to normalize the results, dividing each value by its average (normalization_ma_length, normalization_ma). This will allow comparison between different instruments. For the normalization Moving Average you can choose any currently supported in my lib_no_delay.
get_momentum(momentum_type, sample_type, sample_length, normalization_ma_length, normalization_ma)
Parameters:
momentum_type (series MomentumType) : select one of MomentumType. to sample the price, volume or a product of both
sample_type (series SampleType) : select one of SampleType. to sample the body, total range from high to low or a combination of both (body count full, wicks half for each direction)
sample_length (simple int) : how many candles should be sampled (including the current)
normalization_ma_length (simple int) : if you want to normalize results (momentum / momentum average) this sets the period for the average. (default = 0 => no normalization)
normalization_ma (simple MovingAverage enum from robbatt/lib_no_delay/9) : is the type of moving average to normalize / compare with
Returns: returns the current momentum where the total line is not just (up - down) but also sampled over the sample_length and can therefore be used as trend indicator. If up/down fail to reach total's level it's a sign of decreasing momentum, if up/down exceed total the trend it's a sign of increasing momentum.
analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics
BinaryInsertionSortLibrary "BinaryInsertionSort"
Library containing functions which can help create sorted array based on binary insertion sort.
This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
method binary_search_basic(sortedArray, item, order)
binary_search_basic - finds the closest index of the value
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (float) : float item which needs to be searched in the sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item can be inserted into sorted array
method binary_search_basic(sortedArray, item, order)
binary_search_basic - finds the closest index of the value
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (int) : int item which needs to be searched in the sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item can be inserted into sorted array
method binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (float) : float item which needs to be inserted into sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
method binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (int) : int item which needs to be inserted into sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
update_sort_indices(sortIndices, newItemIndex)
adds the sort index of new item added to sorted array and also updates existing sort indices.
Parameters:
sortIndices (array) : array containing sort indices of an array.
newItemIndex (int) : sort index of new item added to sorted array
Returns: void
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item (float) : float series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item (int) : int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item (float) : float|int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item (int) : int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
lib_no_delayLibrary "lib_no_delay"
This library contains modifications to standard functions that return na before reaching the bar of their 'length' parameter.
That is because they do not compromise speed at current time for correct results in the past. This is good for live trading in short timeframes but killing applications on Monthly / Weekly timeframes if instruments, like in crypto, do not have extensive history (why would you even trade the monthly on a meme coin ... not my decision).
Also, some functions rely on source (value at previous bar), which is not available on bar 1 and therefore cascading to a na value up to the last bar ... which in turn leads to a non displaying indicator and waste of time debugging this)
Anyway ... there you go, let me know if I should add more functions.
sma(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Simple moving average of source for length bars back.
ema(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: (float) The exponentially weighted moving average of the source.
rma(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Exponential moving average of source with alpha = 1 / length.
atr(length)
Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close ), abs(low - close )). This adapted version extends ta.atr to start without delay at first bar and deliver usable data instead of na by averaging ta.tr(true) via manual SMA.
Parameters:
length (simple int) : Number of bars back (length).
Returns: Average true range.
rsi(source, length)
Relative strength index. It is calculated using the ta.rma() of upward and downward changes of source over the last length bars. This adapted version extends ta.rsi to start without delay at first bar and deliver usable data instead of na.
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars back (length).
Returns: Relative Strength Index.
Time Zone CorrectorThe Time Zone Corrector library provides a utility function designed to adjust time based on the user's current time zone. This library supports a wide range of time zones across the Americas, Europe, Asia, and Oceania, making it highly versatile for traders around the world. It simulates a switch-case structure using ternary operators to output the appropriate time offset relative to UTC.
Whether you're dealing with market sessions in New York, Tokyo, London, or other major trading hubs, this library helps ensure your trading algorithms can accurately account for time differences. The library is particularly useful for strategies that rely on precise timing, as it dynamically adjusts the time zone offset depending on the symbol being traded.
iteratorThe "Iterator" library is designed to provide a flexible way to work with sequences of values. This library offers a set of functions to create and manage iterators for various data types, including integers, floats, and more. Whether you need to generate an array of values with specific increments or iterate over elements in reverse order, this library has you covered.
Key Features:
Array Creation: Easily generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
Flexible Iteration: Includes methods to iterate over arrays of different types, such as booleans, integers, floats, strings, colors, and drawing objects like lines and labels.
Reverse Iteration: Support for reverse iteration, giving you control over the order in which elements are processed.
Automatic Loop Control: One of the key advantages of this library is that when using the .iterate() method, it only loops over the array when there are values present. This means you don’t have to manually check if the array is populated before iterating, simplifying your code and reducing potential errors.
Versatile Use Cases: Ideal for scenarios where you need to loop over an array without worrying about empty arrays or checking conditions manually.
This library is particularly useful in cases where you need to perform operations on each element in an array, ensuring that your loops are efficient and free from unnecessary checks.
Library "iterator"
The "iterator" library provides a versatile and efficient set of functions for creating and managing iterators.
It allows you to generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
The library also includes methods for iterating over various types, including booleans, integers, floats, strings, colors,
and drawing objects like lines and labels. With support for reverse iteration and flexible customization options.
iterator(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator_inclusive(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
iterator_inclusive(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
itr(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop.
itr(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop.
itr_in(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
itr_in(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
LibraryBitwiseOperandsLibrary "LibraryBitwiseOperands"
Description: When you need more space for your data you can use bitwise operations. For example if you are creating an Order Block indicator and you have multiple types then you can define variables for each type with only one bit set like these:
const int TYPE_OB = 1
const int TYPE_HH = 2
const int TYPE_LH = 4
const int TYPE_HL = 8
const int TYPE_LL = 16
const int TYPE_BOS = 32
const int TYPE_CHOCH = 64
bitwise_shift_left(x, y)
bitwise_shift_left(): Bitwise left shift: x << y
Parameters:
x (int)
y (int)
Returns: : The left operand’s value is moved toward left by the number of bits specified by the right operand.
bitwise_shift_right(x, y)
bitwise_shift_right(): Bitwise right shift: x >> y
Parameters:
x (int)
y (int)
Returns: : The left operand’s value is moved toward right by the number of bits specified by the right operand.
bitwise_not(x)
bitwise_not(): Bitwise NOT: ~x
Parameters:
x (int)
Returns: : Inverts individual bits.
bitwise_and(x, y)
bitwise_and(): Bitwise AND: x & y
Parameters:
x (int)
y (int)
Returns: : Result bit 1, if both operand bits are 1; otherwise results bit 0.
bitwise_or(x, y)
bitwise_or(): Bitwise OR: x | y
Parameters:
x (int)
y (int)
Returns: : Result bit 1, if any of the operand bit is 1; otherwise results bit 0.
bitwise_xor(x, y)
bitwise_xor(): Bitwise (exclusive OR) XOR: x ^ y
Parameters:
x (int)
y (int)
Returns: : Result bit 1, if any of the operand bit is 1 but not both, otherwise results bit 0.
logical_xor(x, y)
logical_xor(): Logical (exclusive OR) XOR: x xor y
Parameters:
x (bool)
y (bool)
Returns: : Result true, if any of the operand bit are different, otherwise results bit 0.
bit_check(x, y)
bit_check(): Bitwise Checks the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns True if the bit is set.
bit_set(x, y)
bit_set(): Bitwise Sets the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns a value with the bit set.
bit_clear(x, y)
bit_clear(): Bitwise Clears the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns a value with the bit cleared.
bit_flip(x, y)
bit_flip(): Bitwise Inverts the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns a value with the bit inverted.
bitmask_check(x, mask)
bitmask_check(): Bitwise Checks the specified Mask
Parameters:
x (int)
mask (int)
Returns: : Returns True if the mask is set.
bitmask_set(x, mask)
bitmask_set(): Bitwise Sets the specified Mask
Parameters:
x (int)
mask (int)
Returns: : Returns a value with the mask set.
bitmask_clear(x, mask)
bitmask_clear(): Bitwise Clears the specified Mask
Parameters:
x (int)
mask (int)
Returns: : Returns a value with the mask cleared.
bitmask_flip(x, mask)
bitmask_flip(): Inverts the specified Mask
Parameters:
x (int)
mask (int)
Returns: : Returns a value with the mask inverted.
math_bit_check(x, y)
math_bit_check(): Fast arithmetic bitwise Checks the specified Mask
Parameters:
x (int)
y (int)
Returns: : Returns True if the mask is set.
math_bit_set(x, y)
math_bit_set(): Fast arithmetic bitwise Sets the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns a value with the bit set.
math_bit_clear(x, y)
math_bit_clear(): Fast arithmetic bitwise Clears the specified bit
Parameters:
x (int)
y (int)
Returns: : Returns a value with the bit cleared.
math_bitmask_check(x, y)
math_bitmask_check(): Fast arithmetic bitwise Checks the specified Mask
Parameters:
x (int)
y (int)
Returns: : Returns True if the mask is set.
math_bitmask_set(x, y)
math_bitmask_set(): Fast arithmetic bitwise Sets the specified Mask
Parameters:
x (int)
y (int)
Returns: : Returns a value with the mask set.
math_bitmask_clear(x, y)
math_bitmask_clear(): Fast arithmetic bitwise Clears the specified Mask
Parameters:
x (int)
y (int)
Returns: : Returns a value with the mask cleared.
SpectrumLibrary "Spectrum"
This library includes spectrum analysis tools such as the Fast Fourier Transform (FFT).
method toComplex(data, polar)
Creates an array of complex type objects from a float type array.
Namespace types: array
Parameters:
data (array) : The float type array of input data.
polar (bool) : Initialization coordinates; the default is false (cartesian).
Returns: The complex type array of converted data.
method sAdd(data, value, end, start, step)
Performs scalar addition of a given float type array and a simple float value.
Namespace types: array
Parameters:
data (array) : The float type array of input data.
value (float) : The simple float type value to be added.
end (int) : The last index of the input array (exclusive) on which the operation is performed.
start (int) : The first index of the input array (inclusive) on which the operation is performed; the default value is 0.
step (int) : The step by which the function iterates over the input data array between the specified boundaries; the default value is 1.
Returns: The modified input array.
method sMult(data, value, end, start, step)
Performs scalar multiplication of a given float type array and a simple float value.
Namespace types: array
Parameters:
data (array) : The float type array of input data.
value (float) : The simple float type value to be added.
end (int) : The last index of the input array (exclusive) on which the operation is performed.
start (int) : The first index of the input array (inclusive) on which the operation is performed; the default value is 0.
step (int) : The step by which the function iterates over the input data array between the specified boundaries; the default value is 1.
Returns: The modified input array.
method eMult(data, data02, end, start, step)
Performs elementwise multiplication of two given complex type arrays.
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : the first complex type array of input data.
data02 (array type from RezzaHmt/Complex/1) : The second complex type array of input data.
end (int) : The last index of the input arrays (exclusive) on which the operation is performed.
start (int) : The first index of the input arrays (inclusive) on which the operation is performed; the default value is 0.
step (int) : The step by which the function iterates over the input data array between the specified boundaries; the default value is 1.
Returns: The modified first input array.
method eCon(data, end, start, step)
Performs elementwise conjugation on a given complex type array.
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : The complex type array of input data.
end (int) : The last index of the input array (exclusive) on which the operation is performed.
start (int) : The first index of the input array (inclusive) on which the operation is performed; the default value is 0.
step (int) : The step by which the function iterates over the input data array between the specified boundaries; the default value is 1.
Returns: The modified input array.
method zeros(length)
Creates a complex type array of zeros.
Namespace types: series int, simple int, input int, const int
Parameters:
length (int) : The size of array to be created.
method bitReverse(data)
Rearranges a complex type array based on the bit-reverse permutations of its size after zero-padding.
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : The complex type array of input data.
Returns: The modified input array.
method R2FFT(data, inverse)
Calculates Fourier Transform of a time series using Cooley-Tukey Radix-2 Decimation in Time FFT algorithm, wikipedia.org
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : The complex type array of input data.
inverse (int) : Set to -1 for FFT and to 1 for iFFT.
Returns: The modified input array containing the FFT result.
method LBFFT(data, inverse)
Calculates Fourier Transform of a time series using Leo Bluestein's FFT algorithm, wikipedia.org This function is nearly 4 times slower than the R2FFT function in practice.
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : The complex type array of input data.
inverse (int) : Set to -1 for FFT and to 1 for iFFT.
Returns: The modified input array containing the FFT result.
method DFT(data, inverse)
This is the original DFT algorithm. It is not suggested to be used regularly.
Namespace types: array
Parameters:
data (array type from RezzaHmt/Complex/1) : The complex type array of input data.
inverse (int) : Set to -1 for DFT and to 1 for iDFT.
Returns: The complex type array of DFT result.
GraphLibrary "Graph"
Library to collect data and draw scatterplot and heatmap as graph
method init(this)
Initialise Quadrant Data
Namespace types: Quadrant
Parameters:
this (Quadrant) : Quadrant object that needs to be initialised
Returns: current Quadrant object
method init(this)
Initialise Graph Data
Namespace types: Graph
Parameters:
this (Graph) : Graph object that needs to be initialised with 4 Quadrants
Returns: current Graph object
method add(this, data)
Add coordinates to graph
Namespace types: Graph
Parameters:
this (Graph) : Graph object
data (Coordinate) : Coordinates containing x, y data
Returns: current Graph object
method calculate(this)
Calculation required for plotting the graph
Namespace types: Graph
Parameters:
this (Graph) : Graph object
Returns: current Graph object
method paint(this)
Draw graph
Namespace types: Graph
Parameters:
this (Graph) : Graph object
Returns: current Graph object
Coordinate
Coordinates of sample data
Fields:
xValue (series float) : x value of the sample data
yValue (series float) : y value of the sample data
Quadrant
Data belonging to particular quadrant
Fields:
coordinates (array) : Coordinates present in given quadrant
GraphProperties
Properties of Graph that needs to be drawn
Fields:
rows (series int) : Number of rows (y values) in each quadrant
columns (series int) : number of columns (x values) in each quadrant
graphtype (series GraphType) : Type of graph - scatterplot or heatmap
plotColor (series color) : color of plots or heatmap
plotSize (series string) : size of cells in the table
plotchar (series string) : Character to be printed for display of scatterplot
outliers (series int) : Excude the outlier percent of data from calculating the min and max
position (series string) : Table position
bgColor (series color) : graph background color
PlotRange
Range of a plot in terms of x and y values and the number of data points that fall within the Range
Fields:
minX (series float) : min range of X value
maxX (series float) : max range of X value
minY (series float) : min range of Y value
maxY (series float) : max range of Y value
count (series int) : number of samples in the range
Graph
Graph data and properties
Fields:
properties (GraphProperties) : Graph Properties object associated
quadrants (array) : Array containing 4 quadrant data
plotRanges (matrix) : range and count for each cell
xArray (array) : array of x values
yArray (array) : arrray of y values
MarketAnalysisLibrary "MarketAnalysis"
A collection of frequently used market analysis functions in my scripts.
bullFibRet(priceLow, priceHigh, fibLevel)
Calculates a bullish fibonacci retracement value.
Parameters:
priceLow (float) : (float) The lowest price point.
priceHigh (float) : (float) The highest price point.
fibLevel (float) : (float) The fibonacci level to calculate.
Returns: The fibonacci value of the given retracement level.
bearFibRet(priceLow, priceHigh, fibLevel)
Calculates a bearish fibonacci retracement value.
Parameters:
priceLow (float) : (float) The lowest price point.
priceHigh (float) : (float) The highest price point.
fibLevel (float) : (float) The fibonacci level to calculate.
Returns: The fibonacci value of the given retracement level.
bullFibExt(priceLow, priceHigh, thirdPivot, fibLevel)
Calculates a bullish fibonacci extension value.
Parameters:
priceLow (float) : (float) The lowest price point.
priceHigh (float) : (float) The highest price point.
thirdPivot (float) : (float) The third price point.
fibLevel (float) : (float) The fibonacci level to calculate.
Returns: The fibonacci value of the given extension level.
bearFibExt(priceLow, priceHigh, thirdPivot, fibLevel)
Calculates a bearish fibonacci extension value.
Parameters:
priceLow (float) : (float) The lowest price point.
priceHigh (float) : (float) The highest price point.
thirdPivot (float) : (float) The third price point.
fibLevel (float) : (float) The fibonacci level to calculate.
Returns: The fibonacci value of the given extension level.
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.
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.
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
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