hinton_map█ HINTON MAP
This library provides functions to create and display a Hinton Map visualization. A Hinton map uses squares to represent the magnitude and direction of values in a matrix. This library allows you to display multiple ticker/timeframe/indicator combinations on a single chart, using color/boxsize/bnordersize to represent the values used. The values must be from -1.0 to 1.0 in value. 3 different values can be input per square.
Example Usage:
The example below demonstrates how to create a Hinton Map for two symbols (AAPL and MSFT) across three timeframes (1 minute, 5 minutes, and 1 day).
var hintonData = hinton_map.initHintonData(2, 3)
tickers = array.from("AAPL", "MSFT")
timeframes = array.from("1", "5", "1D")
for i = 0 to array.size(tickers) - 1
for j = 0 to array.size(timeframes) - 1
ticker = array.get(tickers, i)
timeframe = array.get(timeframes, j)
= request.security(ticker, timeframe, [close, close , ta.rsi(close, 14)], lookahead = barmerge.lookahead_on)
percent_change = (close_current - close_previous) / close_previous * 100
rsi_deviation = rsi_current - 50
hintonData.unitMatrix.set(i, j, hinton_map.createHintonUnit(
fillValue = percent_change,
borderValue = rsi_deviation,
innerValue = percent_change * rsi_deviation,
boxText = dv.from_string(str.tostring(math.round(percent_change, 2)) + "%"),
tooltipText = dv.from_string(syminfo.ticker + ", " + timeframe + ": " + str.tostring(math.round(percent_change, 2)) + "%, RSI: " + str.tostring(math.round(rsi_current, 2)))
))
hinton_map.drawHintonMap(hintonData)
█ createHintonUnit
Creates a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
Default Value: 0.0
• borderValue
Value to determine the border color hue and width.
Type: float
Default Value: 0.0
• innerValue
Value to determine the inner box color hue.
Type: float
Default Value: 0.0
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
Default Value: na
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
Default Value: na
Returns: HintonUnit
█ initHintonData
Initializes Hinton map data structure.
• rows
Number of rows.
Type: int
• columns
Number of columns.
Type: int
Returns: HintonData
█ drawHintonMap
Draws a Hinton map.
• hintonData
Hinton map data.
Type: HintonData
• unitSize
Size of each unit in bars.
Type: int
Default Value: 10
• borderWidth
Base width of the inner box border.
Type: int
Default Value: 5
• plusHue
Hue value for positive values (0-360).
Type: float
Default Value: 180
• minusHue
Hue value for negative values (0-360).
Type: float
Default Value: -30
█ HintonUnit
Data for a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
• borderValue
Value to determine the border color hue and width.
Type: float
• innerValue
Value to determine the inner box color hue.
Type: float
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
█ HintonData
Structure to store Hinton map data.
• unitMatrix
Matrix of Hinton units.
Type: matrix
• lineMatrix
Matrix of lines.
Type: matrix
• labelMatrix
Matrix of labels.
Type: matrix
• boxMatrix
Matrix of boxes.
Type: matrix
• fillMatrix
Matrix of line fills.
Type: matrix
Indikator dan strategi
SnowdexUtilsLibrary "SnowdexUtils"
the various function that often use when create a strategy trading.
f_backtesting_date(train_start_date, train_end_date, test_date, deploy_date)
Backtesting within a specific window based on deployment and testing dates.
Parameters:
train_start_date (int) : the start date for training the strategy.
train_end_date (int) : the end date for training the strategy.
test_date (bool) : if true, backtests within the period from `train_end_date` to the current time.
deploy_date (bool) : if true, the strategy backtests up to the current time.
Returns: given time falls within the specified window for backtesting.
f_init_ma(ma_type, source, length)
Initializes a moving average based on the specified type.
Parameters:
ma_type (simple string) : the type of moving average (e.g., "RMA", "EMA", "SMA", "WMA").
source (float) : the input series for the moving average calculation.
length (simple int) : the length of the moving average window.
Returns: the calculated moving average value.
f_init_tp(side, entry_price, rr, sl_open_position)
Calculates the target profit based on entry price, risk-reward ratio, and stop loss. The formula is `tp = entry price + (rr * (entry price - stop loss))`.
Parameters:
side (bool) : the trading side (true for long, false for short).
entry_price (float) : the entry price of the position.
rr (float) : the risk-reward ratio.
sl_open_position (float) : the stop loss price for the open position.
Returns: the calculated target profit value.
f_round_up(number, decimals)
Rounds up a number to a specified number of decimals.
Parameters:
number (float)
decimals (int)
Returns: The rounded-up number.
f_get_pip_size()
Calculates the pip size for the current instrument.
Returns: Pip size adjusted for Forex instruments or 1 for others.
f_table_get_position(value)
Maps a string to a table position constant.
Parameters:
value (string) : String representing the desired position (e.g., "Top Right").
Returns: The corresponding position constant or `na` for invalid values.
ArrayMovingAveragesLibrary "ArrayMovingAverages"
This library adds several moving average methods to arrays, so you can call, eg.:
myArray.ema(3)
method emaArray(id, length)
Calculate Exponential Moving Average (EMA) for Arrays
Namespace types: array
Parameters:
id (array) : (array) Input array
length (int) : (int) Length of the EMA
Returns: (array) Array of EMA values
method ema(id, length)
Get the last value of the EMA array
Namespace types: array
Parameters:
id (array) : (array) Input array
length (int) : (int) Length of the EMA
Returns: (float) Last EMA value or na if empty
method rmaArray(id, length)
Calculate Rolling Moving Average (RMA) for Arrays
Namespace types: array
Parameters:
id (array) : (array) Input array
length (int) : (int) Length of the RMA
Returns: (array) Array of RMA values
method rma(id, length)
Get the last value of the RMA array
Namespace types: array
Parameters:
id (array) : (array) Input array
length (int) : (int) Length of the RMA
Returns: (float) Last RMA value or na if empty
method smaArray(id, windowSize)
Calculate Simple Moving Average (SMA) for Arrays
Namespace types: array
Parameters:
id (array) : (array) Input array
windowSize (int) : (int) Window size for calculation, defaults to array size
Returns: (array) Array of SMA values
method sma(id, windowSize)
Get the last value of the SMA array
Namespace types: array
Parameters:
id (array) : (array) Input array
windowSize (int) : (int) Window size for calculation, defaults to array size
Returns: (float) Last SMA value or na if empty
method wmaArray(id, windowSize)
Calculate Weighted Moving Average (WMA) for Arrays
Namespace types: array
Parameters:
id (array) : (array) Input array
windowSize (int) : (int) Window size for calculation, defaults to array size
Returns: (array) Array of WMA values
method wma(id, windowSize)
Get the last value of the WMA array
Namespace types: array
Parameters:
id (array) : (array) Input array
windowSize (int) : (int) Window size for calculation, defaults to array size
Returns: (float) Last WMA value or na if empty
libTFLibrary "libTF"
libTF: Find higher/lower TF automatically
This library to find higher/lower TF from current timeframe(timeframe.period) for Pine Script version6(or higher).
Basic Algorithm
Using a timeframe scale Array and timeframe.in_seconds() function to find higher/lower timeframe.
Return value is na if could not find TF in the timeframe scale.
The timeframe scale could be changed by the parameter 'scale'(CSV).
How to use
1. Set higher/lower TF
higher()/lower() function returns higher/lower TF.
Default timeframe scale is "1, 5, 15, 60, 240, 1D, 1M, 3M, 12M".
example:
htf1 = higher()
htf2 = higher(htf1)
ltf1 = lower()
ltf2 = lower(ltf1)
2. Set higher/lower TF using your timeframe scale
The timeframe scale could be changed by the parameter.
example:
myscale="1,60,1D,1M,12M"
htf1 = higher(timeframe.period,myscale)
htf2 = higher(htf1,myscale)
ltf1 = lower(timeframe.period,myscale)
ltf2 = lower(ltf1,myscale)
3. How to use with request.*() function
na value is set if no higher/lower TF in timeframe scale.
It returns current timeframe's value, when na value as timeframe parameter in request.*().
As bellow, if it should be na when timeframe is na.
example:
return_value_request_htf1 = na(htf1)?na:request.security(syminfo.tickerid,htf1,timeframe.period)
return_value_request_ltf1 = na(ltf1)?na:request.security(syminfo.tickerid,ltf1,timeframe.period)
higher(tf, scale)
higher: find higher TF from TF string.
Parameters:
tf (string) : default value is timeframe.period.
scale (string) : TF scale in CSV. default is "1,5,15,60,240,1D,1W,1M,3M,12M".
Returns: higher TF string.
lower(tf, scale)
lower: find lower TF from TF string.
Parameters:
tf (string) : default value is timeframe.period.
scale (string) : TF scale in CSV. defalut is "1,5,15,60,240,1D,1W,1M,3M,12M".
Returns: lower TF string.
MarketStructureLibrary "MarketStructure"
Will draw out the market structure for the disired pivot length. The code is from my indicator "Marker structure" ().
Create(type, length, source, equalPivotsFactor, extendEqualPivotsZones, equalPivotsStyle, equalPivotsColor, alertFrequency)
Call on each bar. Will create a Structure object.
Parameters:
type (int) : the type of the Structure to create. 0 = internal, 1 = swing.
length (int) : The lenghts (left and right) for pivots to use.
source (string) : The source to be used for structural changes ('Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend)).
equalPivotsFactor (float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
extendEqualPivotsZones (bool) : Set to true if you want the equal pivots zones to be extended.
equalPivotsStyle (string) : Set the style of equal pivot zones.
equalPivotsColor (color) : Set the color of equal pivot zones.
alertFrequency (string)
Returns: The 'structure' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
Returns: The 'structure' object.
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
Returns: The 'structure' object.
EqualHighOrLow(structure)
Draws the boxsa for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
Returns: The 'structure' object.
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
ChangeOfCharacter(structure)
Will create lines when a change of character occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
Structure
Holds all the values for the market structure.
Fields:
Length (series int) : Define the left and right lengths of the pivots used.
Type (series int) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
Source (series string) : Set the source for structural chandeg. Can be 'Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend).
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
AlertFrequency (series string) : set the frequency for alerts.
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
alertsLibrary "alerts"
The library provides options to run alert() calls in loop without worrying about limitations of frequency options.
When an alert statement is called within a loop,
it will fire just once per bar irrespective of how many iterations allowed when fequency is set to alert.freq_once_per_bar or alert.freq_once_per_bar_close
it will fire continuously till it breaks when frequency is set to alert.freq_all
The function helps overcome this issue by using varip key array which resets on every bar
method alert(message, key)
Enhanced alert which can be used in loops
Namespace types: series string, simple string, input string, const string
Parameters:
message (string) : Alert message to be fired
key (string) : Key to be checked to avoid repetitive alerts
Returns: array containing id of already fired alerts
method updateAlertTemplate(this, template)
Updates alert template with given keys and values
Namespace types: map
Parameters:
this (map) : map containing key value pair
template (string) : Alert message template
Returns: updated alert message
utilsLibrary "utils"
Few essentials captured together (subset of arrayutils)
timer(timeStart, timeEnd)
finds difference between two timestamps
Parameters:
timeStart (int) : start timestamp
timeEnd (int)
Returns:
method check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Namespace types: array
Parameters:
pivots (array) : pivots array
barArray (array) : pivot bar array
dir (int) : direction for which overflow need to be checked
Returns: bool overflow
method get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Namespace types: array
Parameters:
pivots (array) : pivots array
length (int) : length for which trend series need to be checked
highLow (int) : filter pivot high or low
trend (int) : Uptrend or Downtrend
Returns: int trendIndexes
method get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Namespace types: array
Parameters:
pivots (array) : pivots array
firstIndex (int) : First index of the series
lastIndex (int) : Last index of the series
Returns: int trendIndexes
getConsolidatedLabel(include, labels, separator)
Consolidates labels into single string by concatenating it with given separator
Parameters:
include (array) : array of conditions to include label or not
labels (array) : string array of labels
separator (string) : Separator for concatenating labels
Returns: string labelText
method getColors(theme)
gets array of colors based on theme
Namespace types: series Theme
Parameters:
theme (series Theme) : dark or light theme
Returns: color themeColors
DeepSignalFilterHelpersLibrary "DeepSignalFilterHelpers"
filter_intraday_intensity(useIiiFilter)
Parameters:
useIiiFilter (bool)
filter_vwma(src, length, useVwmaFilter)
Parameters:
src (float)
length (int)
useVwmaFilter (bool)
filter_nvi(useNviFilter)
Parameters:
useNviFilter (bool)
filter_emv(length, emvThreshold, useEmvFilter, useMovingAvg)
EMV filter for filtering signals based on Ease of Movement
Parameters:
length (int) : The length of the EMV calculation
emvThreshold (float) : The EMV threshold
useEmvFilter (bool) : Whether to apply the EMV filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_adi(length, threshold, useAdiFilter, useMovingAvg)
ADI filter for filtering signals based on Accumulation/Distribution Index
Parameters:
length (int) : The length of the ADI moving average calculation
threshold (float) : The ADI threshold
useAdiFilter (bool) : Whether to apply the ADI filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_mfi(length, mfiThreshold, useMfiFilter, useMovingAvg)
MFI filter for filtering signals based on Money Flow Index
Parameters:
length (int) : The length of the MFI calculation
mfiThreshold (float) : The MFI threshold
useMfiFilter (bool) : Whether to apply the MFI filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
detect_obv_states(obvThresholdStrong, obvThresholdModerate, lookbackPeriod, obvMode)
detect_obv_states: Identify OBV states with three levels (Strong, Moderate, Weak) over a configurable period
Parameters:
obvThresholdStrong (float) : Threshold for strong OBV movements
obvThresholdModerate (float) : Threshold for moderate OBV movements
lookbackPeriod (int) : Number of periods to analyze OBV trends
obvMode (string) : OBV mode to filter ("Strong", "Moderate", "Weak")
Returns: OBV state ("Strong Up", "Moderate Up", "Weak Up", "Positive Divergence", "Negative Divergence", "Consolidation", "Weak Down", "Moderate Down", "Strong Down")
filter_obv(src, length, obvMode, threshold, useObvFilter, useMovingAvg)
filter_obv: Filter signals based on OBV states
Parameters:
src (float) : The source series (default: close)
length (int) : The length of the OBV moving average calculation
obvMode (string) : OBV mode to filter ("Strong", "Moderate", "Weak")
threshold (float) : Optional threshold for additional filtering
useObvFilter (bool) : Whether to apply the OBV filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_cmf(length, cmfThreshold, useCmfFilter, useMovingAvg)
CMF filter for filtering signals based on Chaikin Money Flow
Parameters:
length (int) : The length of the CMF calculation
cmfThreshold (float) : The CMF threshold
useCmfFilter (bool) : Whether to apply the CMF filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_vwap(useVwapFilter)
VWAP filter for filtering signals based on Volume-Weighted Average Price
Parameters:
useVwapFilter (bool) : Whether to apply the VWAP filter
Returns: Filtered result indicating whether the signal should be used
filter_pvt(length, pvtThreshold, usePvtFilter, useMovingAvg)
PVT filter for filtering signals based on Price Volume Trend
Parameters:
length (int) : The length of the PVT moving average calculation
pvtThreshold (float) : The PVT threshold
usePvtFilter (bool) : Whether to apply the PVT filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_vo(shortLength, longLength, voThreshold, useVoFilter, useMovingAvg)
VO filter for filtering signals based on Volume Oscillator
Parameters:
shortLength (int) : The length of the short-term volume moving average
longLength (int) : The length of the long-term volume moving average
voThreshold (float) : The Volume Oscillator threshold
useVoFilter (bool) : Whether to apply the VO filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_cho(shortLength, longLength, choThreshold, useChoFilter, useMovingAvg)
CHO filter for filtering signals based on Chaikin Oscillator
Parameters:
shortLength (int) : The length of the short-term ADI moving average
longLength (int) : The length of the long-term ADI moving average
choThreshold (float) : The Chaikin Oscillator threshold
useChoFilter (bool) : Whether to apply the CHO filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_fi(length, fiThreshold, useFiFilter, useMovingAvg)
FI filter for filtering signals based on Force Index
Parameters:
length (int) : The length of the FI calculation
fiThreshold (float) : The Force Index threshold
useFiFilter (bool) : Whether to apply the FI filter
useMovingAvg (bool) : Whether to use moving average as threshold
Returns: Filtered result indicating whether the signal should be used
filter_garman_klass_volatility(length, useGkFilter)
Parameters:
length (int)
useGkFilter (bool)
filter_frama(src, length, useFramaFilter)
Parameters:
src (float)
length (int)
useFramaFilter (bool)
filter_bollinger_bands(src, length, stdDev, useBollingerFilter)
Parameters:
src (float)
length (int)
stdDev (float)
useBollingerFilter (bool)
filter_keltner_channel(src, length, atrMult, useKeltnerFilter)
Parameters:
src (float)
length (simple int)
atrMult (float)
useKeltnerFilter (bool)
regime_filter(src, threshold, useRegimeFilter)
Regime filter for filtering signals based on trend strength
Parameters:
src (float) : The source series
threshold (float) : The threshold for the filter
useRegimeFilter (bool) : Whether to apply the regime filter
Returns: Filtered result indicating whether the signal should be used
regime_filter_v2(src, threshold, useRegimeFilter)
Regime filter for filtering signals based on trend strength
Parameters:
src (float) : The source series
threshold (float) : The threshold for the filter
useRegimeFilter (bool) : Whether to apply the regime filter
Returns: Filtered result indicating whether the signal should be used
filter_adx(src, length, adxThreshold, useAdxFilter)
ADX filter for filtering signals based on ADX strength
Parameters:
src (float) : The source series
length (simple int) : The length of the ADX calculation
adxThreshold (int) : The ADX threshold
useAdxFilter (bool) : Whether to apply the ADX filter
Returns: Filtered result indicating whether the signal should be used
filter_volatility(minLength, maxLength, useVolatilityFilter)
Volatility filter for filtering signals based on volatility
Parameters:
minLength (simple int) : The minimum length for ATR calculation
maxLength (simple int) : The maximum length for ATR calculation
useVolatilityFilter (bool) : Whether to apply the volatility filter
Returns: Filtered result indicating whether the signal should be used
filter_ulcer(src, length, ulcerThreshold, useUlcerFilter)
Ulcer Index filter for filtering signals based on Ulcer Index
Parameters:
src (float) : The source series
length (int) : The length of the Ulcer Index calculation
ulcerThreshold (float) : The Ulcer Index threshold (default: average Ulcer Index)
useUlcerFilter (bool) : Whether to apply the Ulcer Index filter
Returns: Filtered result indicating whether the signal should be used
filter_stddev(src, length, stdDevThreshold, useStdDevFilter)
Standard Deviation filter for filtering signals based on Standard Deviation
Parameters:
src (float) : The source series
length (int) : The length of the Standard Deviation calculation
stdDevThreshold (float) : The Standard Deviation threshold (default: average Standard Deviation)
useStdDevFilter (bool) : Whether to apply the Standard Deviation filter
Returns: Filtered result indicating whether the signal should be used
filter_macdv(src, shortLength, longLength, signalSmoothing, macdVThreshold, useMacdVFilter)
MACD-V filter for filtering signals based on MACD-V
Parameters:
src (float) : The source series
shortLength (simple int) : The short length for MACD calculation
longLength (simple int) : The long length for MACD calculation
signalSmoothing (simple int) : The signal smoothing length for MACD
macdVThreshold (float) : The MACD-V threshold (default: average MACD-V)
useMacdVFilter (bool) : Whether to apply the MACD-V filter
Returns: Filtered result indicating whether the signal should be used
filter_atr(length, atrThreshold, useAtrFilter)
ATR filter for filtering signals based on Average True Range (ATR)
Parameters:
length (simple int) : The length of the ATR calculation
atrThreshold (float) : The ATR threshold (default: average ATR)
useAtrFilter (bool) : Whether to apply the ATR filter
Returns: Filtered result indicating whether the signal should be used
filter_candle_body_and_atr(length, bodyThreshold, atrThreshold, useFilter)
Candle Body and ATR filter for filtering signals
Parameters:
length (simple int) : The length of the ATR calculation
bodyThreshold (float) : The threshold for candle body size (relative to ATR)
atrThreshold (float) : The ATR threshold (default: average ATR)
useFilter (bool) : Whether to apply the candle body and ATR filter
Returns: Filtered result indicating whether the signal should be used
filter_atrp(length, atrpThreshold, useAtrpFilter)
ATRP filter for filtering signals based on ATR Percentage (ATRP)
Parameters:
length (simple int) : The length of the ATR calculation
atrpThreshold (float) : The ATRP threshold (default: average ATRP)
useAtrpFilter (bool) : Whether to apply the ATRP filter
Returns: Filtered result indicating whether the signal should be used
filter_jma(src, length, phase, useJmaFilter)
Parameters:
src (float)
length (simple int)
phase (float)
useJmaFilter (bool)
filter_cidi(src, rsiLength, shortMaLength, longMaLength, useCidiFilter)
Parameters:
src (float)
rsiLength (simple int)
shortMaLength (int)
longMaLength (int)
useCidiFilter (bool)
filter_rsi(src, length, rsiThreshold, useRsiFilter)
Parameters:
src (float)
length (simple int)
rsiThreshold (float)
useRsiFilter (bool)
filter_ichimoku_oscillator(length, threshold, useFilter)
Ichimoku Oscillator filter for filtering signals based on Ichimoku Oscillator
Parameters:
length (int) : The length of the Ichimoku Oscillator calculation
threshold (float) : The threshold for the filter (default: average Ichimoku Oscillator)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_cmb_composite_index(src, shortLength, longLength, threshold, useFilter)
CMB Composite Index filter for filtering signals based on CMB Composite Index
Parameters:
src (float) : The source series
shortLength (simple int) : The short length for CMB calculation
longLength (simple int) : The long length for CMB calculation
threshold (float) : The threshold for the filter (default: average CMB Composite Index)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_connors_rsi(src, rsiLength, rocLength, streakLength, threshold, useFilter)
Connors RSI filter for filtering signals based on Connors RSI
Parameters:
src (float) : The source series
rsiLength (simple int) : The length for RSI calculation
rocLength (int) : The length for ROC calculation
streakLength (simple int) : The length for streak calculation
threshold (float) : The threshold for the filter (default: average Connors RSI)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_coppock_curve(src, roc1Length, roc2Length, wmaLength, threshold, useFilter)
Coppock Curve filter for filtering signals based on Coppock Curve
Parameters:
src (float) : The source series
roc1Length (int) : The length for the first ROC calculation
roc2Length (int) : The length for the second ROC calculation
wmaLength (int) : The length for the WMA calculation
threshold (float) : The threshold for the filter (default: average Coppock Curve)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_pmo(src, pmoLength, smoothingLength, threshold, useFilter)
DecisionPoint Price Momentum Oscillator filter for filtering signals based on PMO
Parameters:
src (float) : The source series
pmoLength (simple int) : The length for PMO calculation
smoothingLength (simple int) : The smoothing length for PMO
threshold (float) : The threshold for the filter (default: average PMO Oscillator)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_macd(src, shortLength, longLength, signalSmoothing, threshold, useFilter)
MACD filter for filtering signals based on MACD
Parameters:
src (float) : The source series
shortLength (simple int) : The short length for MACD calculation
longLength (simple int) : The long length for MACD calculation
signalSmoothing (simple int) : The signal smoothing length for MACD
threshold (float) : The threshold for the filter (default: average MACD)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_macd_histogram(src, shortLength, longLength, signalSmoothing, threshold, useFilter)
MACD-Histogram filter for filtering signals based on MACD-Histogram
Parameters:
src (float) : The source series
shortLength (simple int) : The short length for MACD calculation
longLength (simple int) : The long length for MACD calculation
signalSmoothing (simple int) : The signal smoothing length for MACD
threshold (float) : The threshold for the filter (default: average MACD-Histogram)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_kst(src, r1, r2, r3, r4, sm1, sm2, sm3, sm4, signalLength, threshold, useFilter)
Pring's Know Sure Thing filter for filtering signals based on KST
Parameters:
src (float) : The source series
r1 (int) : The first ROC length
r2 (int) : The second ROC length
r3 (int) : The third ROC length
r4 (int) : The fourth ROC length
sm1 (int) : The first smoothing length
sm2 (int) : The second smoothing length
sm3 (int) : The third smoothing length
sm4 (int) : The fourth smoothing length
signalLength (int) : The signal line smoothing length
threshold (float) : The threshold for the filter (default: average KST Oscillator)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_special_k(src, r1, r2, r3, r4, sm1, sm2, sm3, sm4, threshold, useFilter)
Pring's Special K filter for filtering signals based on Special K
Parameters:
src (float) : The source series
r1 (int) : The first ROC length
r2 (int) : The second ROC length
r3 (int) : The third ROC length
r4 (int) : The fourth ROC length
sm1 (int) : The first smoothing length
sm2 (int) : The second smoothing length
sm3 (int) : The third smoothing length
sm4 (int) : The fourth smoothing length
threshold (float) : The threshold for the filter (default: average Special K)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_roc_momentum(src, rocLength, momentumLength, threshold, useFilter)
ROC and Momentum filter for filtering signals based on ROC and Momentum
Parameters:
src (float) : The source series
rocLength (int) : The length for ROC calculation
momentumLength (int) : The length for Momentum calculation
threshold (float) : The threshold for the filter (default: average ROC and Momentum)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_rrg_relative_strength(src, length, threshold, useFilter)
RRG Relative Strength filter for filtering signals based on RRG Relative Strength
Parameters:
src (float) : The source series
length (int) : The length for RRG Relative Strength calculation
threshold (float) : The threshold for the filter (default: average RRG Relative Strength)
useFilter (bool) : Whether to apply the filter
Returns: Filtered result indicating whether the signal should be used
filter_alligator(useFilter)
Parameters:
useFilter (bool)
filter_wyckoff(useFilter)
Parameters:
useFilter (bool)
filter_squeeze_momentum(bbLength, bbStdDev, kcLength, kcMult, useFilter)
Parameters:
bbLength (int)
bbStdDev (float)
kcLength (simple int)
kcMult (float)
useFilter (bool)
filter_atr_compression(length, atrThreshold, useFilter)
Parameters:
length (simple int)
atrThreshold (float)
useFilter (bool)
filter_low_volume(length, useFilter)
Parameters:
length (int)
useFilter (bool)
filter_nvi_accumulation(useFilter)
Parameters:
useFilter (bool)
filter_ma_slope(src, length, slopeThreshold, useFilter)
Parameters:
src (float)
length (int)
slopeThreshold (float)
useFilter (bool)
filter_adx_low(len, lensig, adxThreshold, useFilter)
Parameters:
len (simple int)
lensig (simple int)
adxThreshold (int)
useFilter (bool)
filter_choppiness_index(length, chopThreshold, useFilter)
Parameters:
length (int)
chopThreshold (float)
useFilter (bool)
filter_range_detection(length, useFilter)
Parameters:
length (int)
useFilter (bool)
QuantifyPS - 1Library "QuantifyPS"
normdist(z)
Parameters:
z (float) : (float): The z-score for which the CDF is to be calculated.
Returns: (float): The cumulative probability corresponding to the input z-score.
Notes:
- Uses an approximation method for the normal distribution CDF, which is computationally efficient.
- The result is accurate for most practical purposes but may have minor deviations for extreme values of `z`.
Formula:
- Based on the approximation formula:
`Φ(z) ≈ 1 - f(z) * P(t)` if `z > 0`, otherwise `Φ(z) ≈ f(z) * P(t)`,
where:
`f(z) = 0.3989423 * exp(-z^2 / 2)` (PDF of standard normal distribution)
`P(t) = Σ [c * t^i]` with constants `c` and `t = 1 / (1 + 0.2316419 * |z|)`.
Implementation details:
- The approximation uses five coefficients for the polynomial part of the CDF.
- Handles both positive and negative values of `z` symmetrically.
Constants:
- The coefficients and scaling factors are chosen to minimize approximation errors.
gamma(x)
Parameters:
x (float) : (float): The input value for which the Gamma function is to be calculated.
Must be greater than 0. For x <= 0, the function returns `na` as it is undefined.
Returns: (float): Approximation of the Gamma function for the input `x`.
Notes:
- The Lanczos approximation provides a numerically stable and efficient method to compute the Gamma function.
- The function is not defined for `x <= 0` and will return `na` in such cases.
- Uses precomputed Lanczos coefficients for accuracy.
- Includes handling for small numerical inaccuracies.
Formula:
- The Gamma function is approximated as:
`Γ(x) ≈ sqrt(2π) * t^(x + 0.5) * e^(-t) * Σ(p / (x + k))`
where `t = x + g + 0.5` and `p` is the array of Lanczos coefficients.
Implementation details:
- Lanczos coefficients (`p`) are precomputed and stored in an array.
- The summation iterates over these coefficients to compute the final result.
- The constant `g` controls the precision of the approximation (commonly `g = 7`).
t_cdf(t, df)
Parameters:
t (float) : (float): The t-statistic for which the CDF value is to be calculated.
df (int) : (int): Degrees of freedom of the t-distribution.
Returns: (float): Approximate CDF value for the given t-statistic.
Notes:
- This function computes a one-tailed p-value.
- Relies on an approximation formula using gamma functions and standard t-distribution properties.
- May not be as accurate as specialized statistical libraries for extreme values or very high degrees of freedom.
Formula:
- Let `x = df / (t^2 + df)`.
- The approximation formula is derived using:
`CDF(t, df) ≈ 1 - * x^((df + 1) / 2) / 2`,
where Γ represents the gamma function.
Implementation details:
- Computes the gamma ratio for normalization.
- Applies the t-distribution formula for one-tailed probabilities.
tStatForPValue(p, df)
Parameters:
p (float) : (float): P-value for which the t-statistic needs to be calculated.
Must be in the interval (0, 1).
df (int) : (int): Degrees of freedom of the t-distribution.
Returns: (float): The t-statistic corresponding to the given p-value.
Notes:
- If `p` is outside the interval (0, 1), the function returns `na` as an error.
- The function uses binary search with a fixed number of iterations and a defined tolerance.
- The result is accurate to within the specified tolerance (default: 0.0001).
- Relies on the cumulative density function (CDF) `t_cdf` for the t-distribution.
Formula:
- Uses the cumulative density function (CDF) of the t-distribution to iteratively find the t-statistic.
Implementation details:
- `low` and `high` define the search interval for the t-statistic.
- The midpoint (`mid`) is iteratively refined until the difference between the cumulative probability
and the target p-value is smaller than the tolerance.
jarqueBera(n, s, k)
Parameters:
n (float) : (series float): Number of observations in the dataset.
s (float) : (series float): Skewness of the dataset.
k (float) : (series float): Kurtosis of the dataset.
Returns: (float): The Jarque-Bera test statistic.
Formula:
JB = n *
Notes:
- A higher JB value suggests that the data deviates more from a normal distribution.
- The test is asymptotically distributed as a chi-squared distribution with 2 degrees of freedom.
- Use this value to calculate a p-value to determine the significance of the result.
skewness(data)
Parameters:
data (float) : (series float): Input data series.
Returns: (float): The skewness value.
Notes:
- Handles missing values (`na`) by ignoring invalid points.
- Includes error handling for zero variance to avoid division-by-zero scenarios.
- Skewness is calculated as the normalized third central moment of the data.
kurtosis(data)
Parameters:
data (float) : (series float): Input data series.
Returns: (float): The kurtosis value.
Notes:
- Handles missing values (`na`) by ignoring invalid points.
- Includes error handling for zero variance to avoid division-by-zero scenarios.
- Kurtosis is calculated as the normalized fourth central moment of the data.
regression(y, x, lag)
Parameters:
y (float) : (series float): Dependent series (observed values).
x (float) : (series float): Independent series (explanatory variable).
lag (int) : (int): Number of lags applied to the independent series (x).
Returns: (tuple): Returns a tuple containing the following values:
- n: Number of valid observations.
- alpha: Intercept of the regression line.
- beta: Slope of the regression line.
- t_stat: T-statistic for the beta coefficient.
- p_value: Two-tailed p-value for the beta coefficient.
- r_squared: Coefficient of determination (R²) indicating goodness of fit.
- skew: Skewness of the residuals.
- kurt: Kurtosis of the residuals.
Notes:
- Handles missing data (`na`) by ignoring invalid points.
- Includes basic error handling for zero variance and division-by-zero scenarios.
- Computes residual-based statistics (skewness and kurtosis) for model diagnostics.
OrderBlocksLibrary "OrderBlocks"
This is a library I created that creates order blocks. It's originated from my indicator "Order blocks" (). It will return a Zone object that can be used to draw an order block. If you want to see how that is done you can check out my indicar that uses the same logic.
Create(settings)
Creates an order block if one is found according to the settings parameter.
Parameters:
settings (Settings) : set all values in this parameter to define the settings for the order block creation.
Returns: a Zone object if an order block is found, na otherwise
Zone
Fields:
Time (series int)
TimeClose (series int)
High (series float)
Low (series float)
ReactionLimit (series float)
TouchedZone (Zone type from mickes/Touched/14)
Type (series int)
Zones
Fields:
Index (series int)
Maximum (series int)
Zones (array)
Remove (Zone)
Settings
Fields:
TakeOut (series bool)
ReactionFactor (series float)
Type (series string)
ConsecutiveRisingOrFalling (series bool)
FairValueGap (series bool)
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)
MonthlyReturnsTableLibrary "MonthlyReturnsTable"
showMonthlyReturns(show)
显示月度和年度收益率表格
Parameters:
show (bool) : (bool) 是否显示表格
Returns: 返回一个数组,包含是否显示表格的状态和当前月度收益率
GaussianDistributionLibrary "GaussianDistribution"
This library defines a custom type `distr` representing a Gaussian (or other statistical) distribution.
It provides methods to calculate key statistical moments and scores, including mean, median, mode, standard deviation, variance, skewness, kurtosis, and Z-scores.
This library is useful for analyzing probability distributions in financial data.
Disclaimer:
I am not a mathematician, but I have implemented this library to the best of my understanding and capacity. Please be indulgent as I tried to translate statistical concepts into code as accurately as possible. Feedback, suggestions, and corrections are welcome to improve the reliability and robustness of this library.
mean(source, length)
Calculate the mean (average) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
Returns: Mean (μ)
stdev(source, length)
Calculate the standard deviation (σ) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
Returns: Standard deviation (σ)
skewness(source, length, mean, stdev)
Calculate the skewness (γ₁) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Skewness (γ₁)
skewness(source, length)
Overloaded skewness to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Skewness (γ₁)
mode(mean, stdev, skewness)
Estimate mode - Most frequent value in the distribution (approximation based on skewness)
Parameters:
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
@return Mode
mode(source, length)
Overloaded mode to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Mode
median(mean, stdev, skewness)
Estimate median - Middle value of the distribution (approximation)
Parameters:
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
@return Median
median(source, length)
Overloaded median to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Median
variance(stdev)
Calculate variance (σ²) - Square of the standard deviation
Parameters:
stdev (float) : the standard deviation (σ) of the distribution
@return Variance (σ²)
variance(source, length)
Overloaded variance to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Variance (σ²)
kurtosis(source, length, mean, stdev)
Calculate kurtosis (γ₂) - Degree of "tailedness" in the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Kurtosis (γ₂)
kurtosis(source, length)
Overloaded kurtosis to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Kurtosis (γ₂)
normal_score(source, mean, stdev)
Calculate Z-score (standard score) assuming a normal distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Z-Score
normal_score(source, length)
Overloaded normal_score to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
non_normal_score(source, mean, stdev, skewness, kurtosis)
Calculate adjusted Z-score considering skewness and kurtosis
Parameters:
source (float) : Distribution source (typically a price or indicator series)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
kurtosis (float) : the "tailedness" in the distribution
@return Z-Score
non_normal_score(source, length)
Overloaded non_normal_score to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
method init(this)
Initialize all statistical fields of the `distr` type
Namespace types: distr
Parameters:
this (distr)
method init(this, source, length)
Overloaded initializer to set source and length
Namespace types: distr
Parameters:
this (distr)
source (float)
length (int)
distr
Custom type to represent a Gaussian distribution
Fields:
source (series float) : Distribution source (typically a price or indicator series)
length (series int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mode (series float) : Most frequent value in the distribution
median (series float) : Middle value separating the greater and lesser halves of the distribution
mean (series float) : μ (1st central moment) - Average of the distribution
stdev (series float) : σ or standard deviation (square root of the variance) - Measure of dispersion
variance (series float) : σ² (2nd central moment) - Squared standard deviation
skewness (series float) : γ₁ (3rd central moment) - Asymmetry of the distribution
kurtosis (series float) : γ₂ (4th central moment) - Degree of "tailedness" relative to a normal distribution
normal_score (series float) : Z-score assuming normal distribution
non_normal_score (series float) : Adjusted Z-score considering skewness and kurtosis
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.
ToolsMapLibrary "ToolsMap"
Helper functions for map type operations
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (string) : Key to be checked
default (bool) : Default return value when key not found. Default: false
Returns: bool
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (string) : Key to be checked
default (int) : Default return value when key not found. Default: -1
Returns: int
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (string) : Key to be checked
default (float) : Default return value when key not found. Default: -1
Returns: float
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (string) : Key to be checked
default (string) : Default return value when key not found. Default: ''
Returns: string
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (string) : Key to be checked
default (color) : Default return value when key not found. Default: color.white
Returns: color
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (int) : Key to be checked
default (bool) : Default return value when key not found. Default: false
Returns: bool
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (int) : Key to be checked
default (int) : Default return value when key not found. Default: -1
Returns: int
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (int) : Key to be checked
default (float) : Default return value when key not found. Default: -1
Returns: float
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (int) : Key to be checked
default (string) : Default return value when key not found. Default: ''
Returns: string
map_def(container, key, default)
Returns Map key's value with default return value option
Parameters:
container (map) : Map object
key (int) : Key to be checked
default (color) : Default return value when key not found. Default: color.white
Returns: color
RHR_CANDLELibrary "RHR_CANDLE"
Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator based on Jake Bernstein’s principles of Moving Average Channel system.
calc(shortLookback, longLookback)
Calculates Expansion Contraction values.
Parameters:
shortLookback (int) : Integer for the short lookback calculation, defaults to 8
longLookback (int) : Integer for the long lookback calculation, defaults to 32
@return Returns array of Expansion Contraction values
stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong, stdevLookback)
Calculates standard deviation lines based on Expansion Contraction Long and Short values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
stdevLookback (int) : Integer for the standard deviation lookback, defaults to 500
@return Returns array of standard deviation values
trend(positiveShort, negativeShort, positiveLong, negativeLong)
Determines if trend is strong or weak based on Expansion Contraction values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
@return Returns array of boolean values indicating strength or weakness of trend
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.
ToolsLibrary "Tools"
Common tools
movingAverage(maType, maSource, maLength)
dynamically returns MA
Parameters:
maType (string) : ma type
maSource (float) : ma source
maLength (simple int) : ma length
Returns: ta.{sma,rma,ema,wma,vwma,hma}
yptestrsilibLibrary "RSIBackgroundLib"
RSI 배경색 라이브러리
rsi_background(_symbol, _timeframe)
RSI 계산 및 배경색 반환
Parameters:
_symbol (simple string) : string 심볼
_timeframe (simple string) : string 타임프레임
Returns: RSI, RSI MA, RSI MA10, 배경색
RawCuts_01Library "RawCuts_01"
A collection of functions by:
mutantdog
The majority of these are used within published projects, some useful variants have been included here aswell.
This is volume one consisting mainly of smaller functions, predominantly the filters and standard deviations from Weight Gain 4000.
Also included at the bottom are various snippets of related code for demonstration. These can be copied and adjusted according to your needs.
A full up-to-date table of contents is located at the top of the main script.
WEIGHT GAIN FILTERS
A collection of moving average type filters with adjustable volume weighting.
Based upon the two most common methods of volume weighting.
'Simple' uses the standard method in which a basic VWMA is analogous to SMA.
'Elastic' uses exponential method found in EVWMA which is analogous to RMA.
Volume weighting is applied according to an exponent multiplier of input volume.
0 >> volume^0 (unweighted), 1 >> volume^1 (fully weighted), use float values for intermediate weighting.
Additional volume filter switch for smoothing of outlier events.
DIVA MODULAR DEVIATIONS
A small collection of standard and absolute deviations.
Includes the weightgain functionality as above.
Basic modular functionality for more creative uses.
Optional input (ct) for external central tendency (aka: estimator).
Can be assigned to alternative filter or any float value. Will default to internal filter when no ct input is received.
Some other useful or related functions included at the bottom along with basic demonstration use.
weightgain_sma(src, len, xVol, fVol)
Simple Moving Average (SMA): Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Standard Simple Moving Average with Simple Weight Gain applied.
weightgain_hsma(src, len, xVol, fVol)
Harmonic Simple Moving Average (hSMA): Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Harmonic Simple Moving Average with Simple Weight Gain applied.
weightgain_gsma(src, len, xVol, fVol)
Geometric Simple Moving Average (gSMA): Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Geometric Simple Moving Average with Simple Weight Gain applied.
weightgain_wma(src, len, xVol, fVol)
Linear Weighted Moving Average (WMA): Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Basic Linear Weighted Moving Average with Simple Weight Gain applied.
weightgain_hma(src, len, xVol, fVol)
Hull Moving Average (HMA): Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Basic Hull Moving Average with Simple Weight Gain applied.
diva_sd_sma(src, len, xVol, fVol, ct)
Standard Deviation (SD SMA): Diva / Weight Gain (Simple Volume)
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_sma().
Returns:
diva_sd_wma(src, len, xVol, fVol, ct)
Standard Deviation (SD WMA): Diva / Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_wma().
Returns:
diva_aad_sma(src, len, xVol, fVol, ct)
Average Absolute Deviation (AAD SMA): Diva / Weight Gain (Simple Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_sma().
Returns:
diva_aad_wma(src, len, xVol, fVol, ct)
Average Absolute Deviation (AAD WMA): Diva / Weight Gain (Simple Volume) .
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_wma().
Returns:
weightgain_ema(src, len, xVol, fVol)
Exponential Moving Average (EMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Exponential Moving Average with Elastic Weight Gain applied.
weightgain_dema(src, len, xVol, fVol)
Double Exponential Moving Average (DEMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Double Exponential Moving Average with Elastic Weight Gain applied.
weightgain_tema(src, len, xVol, fVol)
Triple Exponential Moving Average (TEMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Triple Exponential Moving Average with Elastic Weight Gain applied.
weightgain_rma(src, len, xVol, fVol)
Rolling Moving Average (RMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Rolling Moving Average with Elastic Weight Gain applied.
weightgain_drma(src, len, xVol, fVol)
Double Rolling Moving Average (DRMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Double Rolling Moving Average with Elastic Weight Gain applied.
weightgain_trma(src, len, xVol, fVol)
Triple Rolling Moving Average (TRMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: Triple Rolling Moving Average with Elastic Weight Gain applied.
diva_sd_ema(src, len, xVol, fVol, ct)
Standard Deviation (SD EMA): Diva / Weight Gain: (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_ema().
Returns:
diva_sd_rma(src, len, xVol, fVol, ct)
Standard Deviation (SD RMA): Diva / Weight Gain: (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_rma().
Returns:
weightgain_vidya_rma(src, len, xVol, fVol)
VIDYA v1 RMA base (VIDYA-RMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: VIDYA v1, RMA base with Elastic Weight Gain applied.
weightgain_vidya_ema(src, len, xVol, fVol)
VIDYA v1 EMA base (VIDYA-EMA): Weight Gain (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
Returns: VIDYA v1, EMA base with Elastic Weight Gain applied.
diva_sd_vidya_rma(src, len, xVol, fVol, ct)
Standard Deviation (SD VIDYA-RMA): Diva / Weight Gain: (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_vidya_rma().
Returns:
diva_sd_vidya_ema(src, len, xVol, fVol, ct)
Standard Deviation (SD VIDYA-EMA): Diva / Weight Gain: (Elastic Volume).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
xVol (float) : Volume exponent multiplier (0 = unweighted, 1 = fully weighted).
fVol (bool) : Volume smoothing filter.
ct (float) : Central tendency (optional, na = bypass). Internal: weightgain_vidya_ema().
Returns:
weightgain_sema(src, len, xVol, fVol)
Parameters:
src (float)
len (simple int)
xVol (float)
fVol (bool)
diva_sd_sema(src, len, xVol, fVol)
Parameters:
src (float)
len (simple int)
xVol (float)
fVol (bool)
diva_mad_mm(src, len, ct)
Median Absolute Deviation (MAD MM): Diva (no volume weighting).
Parameters:
src (float) : Source input.
len (int) : Length (number of bars).
ct (float) : Central tendency (optional, na = bypass). Internal: ta.median()
Returns:
source_switch(slct, aux1, aux2, aux3, aux4)
Custom Source Selector/Switch function. Features standard & custom 'weighted' sources with additional aux inputs.
Parameters:
slct (string) : Choose from custom set of string values.
aux1 (float) : Additional input for user-defined source, eg: standard input.source(). Optional, use na to bypass.
aux2 (float) : Additional input for user-defined source, eg: standard input.source(). Optional, use na to bypass.
aux3 (float) : Additional input for user-defined source, eg: standard input.source(). Optional, use na to bypass.
aux4 (float) : Additional input for user-defined source, eg: standard input.source(). Optional, use na to bypass.
Returns: Float value, to be used as src input for other functions.
colour_gradient_ma_div(ma1, ma2, div, bull, bear, mid, mult)
Colour Gradient for plot fill between two moving averages etc, with seperate bull/bear and divergence strength.
Parameters:
ma1 (float) : Input for fast moving average (eg: bullish when above ma2).
ma2 (float) : Input for slow moving average (eg: bullish when below ma1).
div (float) : Input deviation/divergence value used to calculate strength of colour.
bull (color) : Colour when ma1 above ma2.
bear (color) : Colour when ma1 below ma2.
mid (color) : Neutral colour when ma1 = ma2.
mult (int) : Opacity multiplier. 100 = maximum, 0 = transparent.
Returns: Colour with transparency (according to specified inputs)
CandlestickPatternsLibrary "CandlestickPatterns"
zigzag(_low, _high, depth, deviation, backstep)
Parameters:
_low (float)
_high (float)
depth (int)
deviation (int)
backstep (int)
getTrend(trendType, currentClose, zz_downtrend, zz_uptrend, ema14, ema28)
Parameters:
trendType (string)
currentClose (float)
zz_downtrend (bool)
zz_uptrend (bool)
ema14 (float)
ema28 (float)
isInside(currentHigh, currentLow, currentClose, currentOpen, prevHigh, prevLow)
Parameters:
currentHigh (float)
currentLow (float)
currentClose (float)
currentOpen (float)
prevHigh (float)
prevLow (float)
checkMorningStar(open0, high0, low0, close0, open1, high1, low1, close1, open2, high2, low2, close2, innerCandleThreshold, closingMinThreshold, closingMaxThreshold, useDojiFilter, dojiSize, downTrend)
Parameters:
open0 (float)
high0 (float)
low0 (float)
close0 (float)
open1 (float)
high1 (float)
low1 (float)
close1 (float)
open2 (float)
high2 (float)
low2 (float)
close2 (float)
innerCandleThreshold (float)
closingMinThreshold (float)
closingMaxThreshold (float)
useDojiFilter (bool)
dojiSize (float)
downTrend (bool)
checkEveningStar(open0, high0, low0, close0, open1, high1, low1, close1, open2, high2, low2, close2, innerCandleThreshold, closingMinThreshold, closingMaxThreshold, useDojiFilter, dojiSize, upTrend)
Parameters:
open0 (float)
high0 (float)
low0 (float)
close0 (float)
open1 (float)
high1 (float)
low1 (float)
close1 (float)
open2 (float)
high2 (float)
low2 (float)
close2 (float)
innerCandleThreshold (float)
closingMinThreshold (float)
closingMaxThreshold (float)
useDojiFilter (bool)
dojiSize (float)
upTrend (bool)
checkHammerPattern(open, high, low, close, bodyAvg, shadowFactor, downTrend)
Parameters:
open (float)
high (float)
low (float)
close (float)
bodyAvg (float)
shadowFactor (float)
downTrend (bool)
checkInvertedHammerPattern(open, high, low, close, bodyAvg, shadowFactor, downTrend)
Parameters:
open (float)
high (float)
low (float)
close (float)
bodyAvg (float)
shadowFactor (float)
downTrend (bool)
checkHangingManPattern(open, high, low, close, bodyAvg, shadowFactor, upTrend)
Parameters:
open (float)
high (float)
low (float)
close (float)
bodyAvg (float)
shadowFactor (float)
upTrend (bool)
checkShootingStarPattern(open, high, low, close, bodyAvg, shadowFactor, upTrend)
Parameters:
open (float)
high (float)
low (float)
close (float)
bodyAvg (float)
shadowFactor (float)
upTrend (bool)
checkLevels(high0, high1, high2, low0, low1, low2, lookbackPeriod)
Parameters:
high0 (float)
high1 (float)
high2 (float)
low0 (float)
low1 (float)
low2 (float)
lookbackPeriod (int)
CustomAlertLibLibrary "CustomAlertLib"
Custom alert formatting library
customAlert(format, message, freq)
Formats and triggers custom alerts with placeholders
Parameters:
format (string) : String containing the alert format template
message (string) : String containing the alert message
freq (simple string) : (optional) Alert frequency as string, defaults to "once_per_bar_close"
Returns: void